Mercurial > public > sg101
annotate core/image.py @ 590:ce73771b6cd0
Merge.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Thu, 10 May 2012 20:32:19 -0500 |
parents | ee87ea74d46b |
children | 234726f5a47a |
rev | line source |
---|---|
bgneal@265 | 1 """ |
bgneal@265 | 2 This file contains common utility functions for manipulating images for |
bgneal@265 | 3 the rest of the applications in the project. |
bgneal@265 | 4 """ |
bgneal@265 | 5 from PIL import ImageFile |
bgneal@265 | 6 from PIL import Image |
bgneal@265 | 7 |
bgneal@265 | 8 |
bgneal@265 | 9 def parse_image(file): |
bgneal@265 | 10 """ |
bgneal@265 | 11 Returns a PIL Image from the supplied Django file object. |
bgneal@265 | 12 Throws IOError if the file does not parse as an image file or some other |
bgneal@265 | 13 I/O error occurred. |
bgneal@265 | 14 |
bgneal@265 | 15 """ |
bgneal@265 | 16 parser = ImageFile.Parser() |
bgneal@265 | 17 for chunk in file.chunks(): |
bgneal@265 | 18 parser.feed(chunk) |
bgneal@265 | 19 image = parser.close() |
bgneal@265 | 20 return image |
bgneal@265 | 21 |
bgneal@265 | 22 |
bgneal@265 | 23 def downscale_image_square(image, size): |
bgneal@265 | 24 """ |
bgneal@265 | 25 Scale an image to the square dimensions given by size (in pixels). |
bgneal@265 | 26 The new image is returned. |
bgneal@265 | 27 If the image is already smaller than (size, size) then no scaling |
bgneal@265 | 28 is performed and the image is returned unchanged. |
bgneal@265 | 29 |
bgneal@265 | 30 """ |
bgneal@265 | 31 # don't upscale |
bgneal@265 | 32 if (size, size) >= image.size: |
bgneal@265 | 33 return image |
bgneal@265 | 34 |
bgneal@265 | 35 (w, h) = image.size |
bgneal@265 | 36 if w > h: |
bgneal@265 | 37 diff = (w - h) / 2 |
bgneal@265 | 38 image = image.crop((diff, 0, w - diff, h)) |
bgneal@265 | 39 elif h > w: |
bgneal@265 | 40 diff = (h - w) / 2 |
bgneal@265 | 41 image = image.crop((0, diff, w, h - diff)) |
bgneal@265 | 42 image = image.resize((size, size), Image.ANTIALIAS) |
bgneal@265 | 43 return image |