diff gpp/core/image.py @ 265:1ba2c6bf6eb7

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.
author Brian Neal <bgneal@gmail.com>
date Fri, 24 Sep 2010 02:12:09 +0000
parents
children
line wrap: on
line diff
--- /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