Created
October 3, 2013 15:25
-
-
Save bkonkle/6811691 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from io import BytesIO | |
try: | |
from PIL import Image as PILImage | |
except ImportError: | |
try: | |
import Image as PILImage | |
except ImportError: | |
raise ImportError("The Python Imaging Library was not found.") | |
from django.conf import settings | |
from django.utils.timezone import now, make_aware, get_current_timezone | |
from filer.models.imagemodels import Image | |
class CloudImage(Image): | |
class Meta: | |
proxy = True | |
def save(self, *args, **kwargs): | |
""" | |
Mostly copied & pasted from the latest version of django-filer. The | |
intent is to grab the whole image and pass it to PIL in memory, so that | |
it does not generate an HTTP request for each byte. | |
""" | |
if self.date_taken is None: | |
try: | |
exif_date = self.exif.get('DateTimeOriginal', None) | |
if exif_date is not None: | |
d, t = exif_date.split(" ") | |
year, month, day = d.split(':') | |
hour, minute, second = t.split(':') | |
if getattr(settings, "USE_TZ", False): | |
tz = get_current_timezone() | |
self.date_taken = make_aware(datetime( | |
int(year), int(month), int(day), | |
int(hour), int(minute), int(second)), tz) | |
else: | |
self.date_taken = datetime( | |
int(year), int(month), int(day), | |
int(hour), int(minute), int(second)) | |
except Exception: | |
pass | |
if self.date_taken is None: | |
self.date_taken = now() | |
self.has_all_mandatory_data = self._check_validity() | |
try: | |
# Pull the entire file and place it into a BytesIO object to keep | |
# it in memory but interact with it as a file. | |
_file = BytesIO(self.file.read()) | |
self.file.seek(0) | |
self._width, self._height = PILImage.open(_file).size | |
except Exception: | |
# probably the image is missing. nevermind. | |
pass | |
# Intentionally bypass the save method from the original filer Image | |
# by using the superclass of Image instead of CloudImage. | |
super(Image, self).save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment