Login

Async PIL resize of images

Author:
FarmKing
Posted:
February 13, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Call resize_image to replace the image with a resized and normalized version of itself. I recommend doing this with celery, but you could also hook it up to the admin interface if you're not impatient.

 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.