bgneal@265: """ bgneal@265: This file contains common utility functions for manipulating images for bgneal@265: the rest of the applications in the project. bgneal@265: """ bgneal@265: from PIL import ImageFile bgneal@265: from PIL import Image bgneal@265: bgneal@265: bgneal@265: def parse_image(file): bgneal@265: """ bgneal@265: Returns a PIL Image from the supplied Django file object. bgneal@265: Throws IOError if the file does not parse as an image file or some other bgneal@265: I/O error occurred. bgneal@265: bgneal@265: """ bgneal@265: parser = ImageFile.Parser() bgneal@265: for chunk in file.chunks(): bgneal@265: parser.feed(chunk) bgneal@265: image = parser.close() bgneal@265: return image bgneal@265: bgneal@265: bgneal@265: def downscale_image_square(image, size): bgneal@265: """ bgneal@265: Scale an image to the square dimensions given by size (in pixels). bgneal@265: The new image is returned. bgneal@265: If the image is already smaller than (size, size) then no scaling bgneal@265: is performed and the image is returned unchanged. bgneal@265: bgneal@265: """ bgneal@265: # don't upscale bgneal@265: if (size, size) >= image.size: bgneal@265: return image bgneal@265: bgneal@265: (w, h) = image.size bgneal@265: if w > h: bgneal@265: diff = (w - h) / 2 bgneal@265: image = image.crop((diff, 0, w - diff, h)) bgneal@265: elif h > w: bgneal@265: diff = (h - w) / 2 bgneal@265: image = image.crop((0, diff, w, h - diff)) bgneal@265: image = image.resize((size, size), Image.ANTIALIAS) bgneal@265: return image