Login

Async PIL resize of images

Author:
FarmKing
Posted:
February 13, 2012
Language:
Python
Version:
1.3
Tags:
Images PIL
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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months, 1 week ago
  2. Crispy Form by sourabhsinha396 7 months ago
  3. ReadOnlySelect by mkoistinen 7 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 8 months, 1 week ago
  5. Django Language Middleware by agusmakmun 8 months, 3 weeks ago

Comments

Please login first before commenting.