from PIL import Image from cStringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFile import os import urllib2 as urllib class ThingWithTwoImages(models.Model): logo = models.ImageField( blank = True, null = True, verbose_name = _("100x100 image"), ) large_logo = models.ImageField( blank = True, null = True, verbose_name = _("249x159 image"), ) def _resize_image(self, size=(200,200), image=None, image_name="image"): if image: orig_image = image else: orig_image = getattr(self, image_name) print orig_image.name try: pw = orig_image.width ph = orig_image.height nw = size[0] nh = size[1] if (pw, ph) != (nw, nh): pr = float(pw) / float(ph) nr = float(nw) / float(nh) '''Open original photo which we want to resize using PIL's Image object''' img_file = urllib.urlopen(orig_image.url) im = StringIO(img_file.read()) image = Image.open(im) 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)) image = image.crop((0, t, nw, t + nh)) else: # photo aspect matches the destination ratio image = image.resize(size, Image.ANTIALIAS) '''Convert to RGB if necessary''' if image.mode not in ('L', 'RGB'): image = image.convert('RGB') '''Save the resized image''' temp_handle = StringIO() image.save(temp_handle, 'jpeg') temp_handle.seek(0) ''' Save to the image field''' suf = SimpleUploadedFile(os.path.split(orig_image.name)[-1].split('.')[0], temp_handle.read(), content_type='image/jpeg') return suf #self.image.save('%s.jpg' % suf.name, suf, save=True) except (IOError, ValueError, AttributeError): pass return None def resize_image(self, field=None, new_size=None): image = getattr(self, field) if image: if (image.width, image.height) != new_size: new_image = self._resize_image(size=new_size, image=image) if new_image: image.save('%s.jpg' % new_image.name, new_image, save=True) def resize_images(self): resize_image(self, field="large_logo", new_size=(249,159)) resize_image(self, field="logo", new_size=(100,100))