Login

Dynamic Thumbnail for ImageField

Author:
agusmakmun
Posted:
January 21, 2016
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

Dynamic Thumbnail for ImageField with Pillow.

 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
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage as storage
from PIL import Image
import os

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO



class DynamicThumbnail(object):
    """
    param: `self.width` is width of image that will convert to thumbnail.
    param: `self.height` is height of image that will convert to thumbnail.
    param: `self.image_field` is field for models with ImageField, egg: cover = models.ImageField(upload_to='something/')
    param: `self.thumbnail_field` is field for models width ImageField but for thumbnail. egg: thumbnail = models.ImageField(upload_to='something/', editable=False)

    ## Output: egg input `summon_agus.png` and then output thumbnail is `summon_agus.png` but different location as you want.

    ## Example implementation:
    from dynamic_thumbnail import DynamicThumbnail

    class Product(models.Model):
        cover = models.ImageField(upload_to='images/cover/%Y/%m/%d')
        thumbnail = models.ImageField(upload_to='images/cover/thumbnail/%Y/%m/%d', editable=False)
        .....

        def save(self, *args, **kwargs):
            super(Product, self).save(*args, **kwargs)
            if not DynamicThumbnail(110, 150, self.cover, self.thumbnail).make_thumbnail():
                raise Exception('Could not create thumbnail - is the file type valid?')
    """

    def __init__(self, width, height, image_field, thumbnail_field):
        self.width = width
        self.height = height
        self.image_field = image_field
        self.thumbnail_field = thumbnail_field

    def make_thumbnail(self):
        THUMB_SIZE = (self.width, self.height)

        fh = storage.open(self.image_field.name, 'r') 
        try:
            image = Image.open(fh)
        except:
            return False

        image.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
        fh.close()

        thumb_name, thumb_extension = os.path.splitext(self.image_field.name)
        thumb_extension = thumb_extension.lower()
        thumb_filename = thumb_name + thumb_extension

        if thumb_extension in ['.jpg', '.jpeg']:
            FTYPE = 'JPEG'
        elif thumb_extension == '.gif':
            FTYPE = 'GIF'
        elif thumb_extension == '.png':
            FTYPE = 'PNG'
        else:
            return False

        temp_thumb = StringIO()
        image.save(temp_thumb, FTYPE)
        temp_thumb.seek(0)
        self.thumbnail_field.save(thumb_filename, ContentFile(temp_thumb.read()), save=False)
        temp_thumb.close()

        return True

More like this

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

Comments

Please login first before commenting.