comparison core/image.py @ 581:ee87ea74d46b

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