def fit file_path max_width max_height Resize file located on file pat

 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
def fit(file_path, max_width, max_height):
"""Resize file (located on file path) to maximum dimensions proportionally.
At least one of max_width and max_height must be not None."""
if not (max_width or max_height):
# Can't resize
return
img = Image.open(file_path)
w, h = img.size
w = int(max_width or w)
h = int(max_height or h)
img.thumbnail((w, h), Image.ANTIALIAS)
img.save(file_path)
class ImprovedImageField(ImageField):
"""Field supports automatic resizing, if at least one of
max_width and max_height supplied.
"""
def __init__(self, max_width=None, max_height=None, **kwargs):
self.max_width, self.max_height = max_width, max_height
super(ImprovedImageField, self).__init__(**kwargs)
def db_type(self):
"""Required by Django for ORM."""
return 'varchar(100)'
def contribute_to_class(self, cls, name):
"""Hook up events so we can access the instance."""
super(ImprovedImageField, self).contribute_to_class(cls, name)
signals.post_save.connect(self._resize, sender=cls)
def _resize(self, instance, **kwargs):
field = getattr(instance, self.attname)
if field:
if os.path.isfile(field.path):
fit(field.path, self.max_width, self.max_height)