# HG changeset patch # User Brian Neal # Date 1285294329 0 # Node ID 1ba2c6bf6eb77304df5851b61684226a846520b1 # Parent 91c0902de04dc65f022726d483c847b50770eafc Closing #98. Animated GIFs were losing their transparency and animated properties when saved as avatars. Reworked the avatar save process to only run the avatar through PIL if it is too big. This preserves the original uploaded file if it is within the desired size settings. This may still mangle big animated gifs. If this becomes a problem, then maybe look into calling the PIL Image.resize() method directly. Moved the PIL image specific functions from bio.forms to a new module: core.image for better reusability in the future. diff -r 91c0902de04d -r 1ba2c6bf6eb7 gpp/bio/forms.py --- a/gpp/bio/forms.py Thu Sep 23 01:16:26 2010 +0000 +++ b/gpp/bio/forms.py Fri Sep 24 02:12:09 2010 +0000 @@ -1,9 +1,6 @@ """ This file contains the forms used by the bio application. """ -from PIL import ImageFile -from PIL import Image - try: from cStringIO import StringIO except: @@ -16,6 +13,7 @@ from bio.models import UserProfile from core.widgets import AutoCompleteUserInput +from core.image import parse_image, downscale_image_square class EditUserForm(forms.ModelForm): @@ -54,66 +52,51 @@ ('js/bio.js', 'js/timezone.js') -def get_image(file): - """ - Returns a PIL Image from the supplied file. - Throws ValidationError if the file does not parse as an image file. - """ - parser = ImageFile.Parser() - for chunk in file.chunks(): - parser.feed(chunk) - try: - image = parser.close() - return image - except IOError: - pass - raise forms.ValidationError("Upload a valid image. " + - "The file you uploaded was either not an image or a corrupted image.") - - -def scale_image(image, size): - """Scales an image file if necessary.""" - - # don't upscale - if (size, size) >= image.size: - return image - - (w, h) = image.size - if w > h: - diff = (w - h) / 2 - image = image.crop((diff, 0, w - diff, h)) - elif h > w: - diff = (h - w) / 2 - image = image.crop((0, diff, w, h - diff)) - image = image.resize((size, size), Image.ANTIALIAS) - return image - - class UploadAvatarForm(forms.Form): """Form used to change a user's avatar""" avatar_file = forms.ImageField(required=False) image = None def clean_avatar_file(self): - file = self.cleaned_data['avatar_file'] - if file is not None: - if file.size > settings.MAX_AVATAR_SIZE_BYTES: - raise forms.ValidationError("Please upload a file smaller than %s bytes." % \ - settings.MAX_AVATAR_SIZE) - self.image = get_image(file) - self.format = self.image.format - return file + f = self.cleaned_data['avatar_file'] + if f is not None: + if f.size > settings.MAX_AVATAR_SIZE_BYTES: + raise forms.ValidationError("Please upload a file smaller than " + "%s bytes." % settings.MAX_AVATAR_SIZE) + try: + self.image = parse_image(f) + except IOError: + raise forms.ValidationError("Please upload a valid image. " + "The file you uploaded was either not an image or a " + "corrupted image.") + self.file_type = self.image.format + return f - def get_file(self): - if self.image is not None: - self.image = scale_image(self.image, settings.MAX_AVATAR_SIZE_PIXELS) + def save(self): + """ + Perform any down-scaling needed on the new file, then return a tuple of + (filename, file object). Note that the file object returned may not + have a name; use the returned filename instead. + + """ + if not self.cleaned_data['avatar_file']: + return None, None + + name = self.cleaned_data['avatar_file'].name + dim = settings.MAX_AVATAR_SIZE_PIXELS + max_size = (dim, dim) + if self.image and self.image.size > max_size: + self.image = downscale_image_square(self.image, dim) + + # We need to return a Django File now. To get that from here, + # write the image data info a StringIO and then construct a + # Django ContentFile from that. The ContentFile has no name, + # that is why we return one ourselves explicitly. s = StringIO() - self.image.save(s, self.format) - return ContentFile(s.getvalue()) - return None - - def get_filename(self): - return self.cleaned_data['avatar_file'].name + self.image.save(s, self.file_type) + return name, ContentFile(s.getvalue()) + + return name, self.cleaned_data['avatar_file'] class SearchUsersForm(forms.Form): diff -r 91c0902de04d -r 1ba2c6bf6eb7 gpp/bio/views.py --- a/gpp/bio/views.py Thu Sep 23 01:16:26 2010 +0000 +++ b/gpp/bio/views.py Fri Sep 24 02:12:09 2010 +0000 @@ -144,12 +144,21 @@ if request.method == 'POST': form = UploadAvatarForm(request.POST, request.FILES) if form.is_valid(): + # Update the profile with the new avatar profile = request.user.get_profile() - file = form.get_file() + + # First delete any old avatar file if profile.avatar.name != '': profile.avatar.delete(save=False) - if file is not None: - profile.avatar.save(form.get_filename(), file, save=False) + + try: + name, avatar = form.save() + except IOError: + messages.error(request, 'A file error occurred.') + return HttpResponseRedirect(reverse('bio-me')) + + if avatar is not None: + profile.avatar.save(name, avatar, save=False) profile.save() messages.success(request, 'Avatar updated') diff -r 91c0902de04d -r 1ba2c6bf6eb7 gpp/core/image.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/gpp/core/image.py Fri Sep 24 02:12:09 2010 +0000 @@ -0,0 +1,43 @@ +""" +This file contains common utility functions for manipulating images for +the rest of the applications in the project. +""" +from PIL import ImageFile +from PIL import Image + + +def parse_image(file): + """ + Returns a PIL Image from the supplied Django file object. + Throws IOError if the file does not parse as an image file or some other + I/O error occurred. + + """ + parser = ImageFile.Parser() + for chunk in file.chunks(): + parser.feed(chunk) + image = parser.close() + return image + + +def downscale_image_square(image, size): + """ + Scale an image to the square dimensions given by size (in pixels). + The new image is returned. + If the image is already smaller than (size, size) then no scaling + is performed and the image is returned unchanged. + + """ + # don't upscale + if (size, size) >= image.size: + return image + + (w, h) = image.size + if w > h: + diff = (w - h) / 2 + image = image.crop((diff, 0, w - diff, h)) + elif h > w: + diff = (h - w) / 2 + image = image.crop((0, diff, w, h - diff)) + image = image.resize((size, size), Image.ANTIALIAS) + return image