1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 | from PIL import Image
from django.db import models
class Photo(models.Model):
photo = models.ImageField(upload_to='photos')
def save(self, size=(200, 200)):
"""
REQUIRES:
1. 'from PIL import Image'
DOES:
1. check to see if the image needs to be resized
2. check how to resize the image based on its aspect ratio
3. resize the image accordingly
ABOUT:
based loosely on djangosnippet #688
http://www.djangosnippets.org/snippets/688/
VERSIONS I'M WORKING WITH:
Django 1.0
Python 2.5.1
BY:
Tanner Netterville
tanner@cabedge.com
"""
if not self.id and not self.photo:
return
super(Photo, self).save()
pw = self.photo.width
ph = self.photo.height
nw = size[0]
nh = size[1]
# only do this if the image needs resizing
if (pw, ph) != (nw, nh):
filename = str(self.photo.path)
image = Image.open(filename)
pr = float(pw) / float(ph)
nr = float(nw) / float(nh)
if pr > nr:
# photo aspect is wider than destination ratio
tw = int(round(nh * pr))
image = image.resize((tw, nh), Image.ANTIALIAS)
l = int(round(( tw - nw ) / 2.0))
image = image.crop((l, 0, l + nw, nh))
elif pr < nr:
# photo aspect is taller than destination ratio
th = int(round(nw / pr))
image = image.resize((nw, th), Image.ANTIALIAS)
t = int(round(( th - nh ) / 2.0))
print((0, t, nw, t + nh))
image = image.crop((0, t, nw, t + nh))
else:
# photo aspect matches the destination ratio
image = image.resize(size, Image.ANTIALIAS)
image.save(filename)
|
Comments