Login

ImageField with specified maximum image size

Author:
virhilo
Posted:
March 21, 2010
Language:
Python
Version:
1.1
Tags:
image thumbnail imagefield limit size max
Score:
2 (after 2 ratings)

You can specyfy max width and height which image can have, and it never exceed that size.

 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
# -*- coding: utf-8 -*-
from PIL import Image

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

from django.db.models.fields.files import ImageField, ImageFieldFile
from django.core.files.base import ContentFile


def _update_ext(filename, new_ext):
    parts = filename.split('.')
    parts[-1] = new_ext
    return '.'.join(parts)


class ResizedImageFieldFile(ImageFieldFile):
    
    def save(self, name, content, save=True):
        new_content = StringIO()
        content.file.seek(0)

        img = Image.open(content.file)
        img.thumbnail((
            self.field.max_width, 
            self.field.max_height
            ), Image.ANTIALIAS)
        img.save(new_content, format=self.field.format)

        new_content = ContentFile(new_content.getvalue())
        new_name = _update_ext(name, self.field.format.lower())

        super(ResizedImageFieldFile, self).save(new_name, new_content, save)


class ResizedImageField(ImageField):
    
    attr_class = ResizedImageFieldFile

    def __init__(self, max_width=100, max_height=100, format='PNG', *args, **kwargs):
        self.max_width = max_width
        self.max_height = max_height
        self.format = format
        super(ResizedImageField, self).__init__(*args, **kwargs)

More like this

  1. Validate by file content type and size by macmichael01 6 years, 2 months ago
  2. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 3 years, 11 months ago
  3. Image Standarization by garcia_marc 7 years ago
  4. django-thumbs black&white support by rdugo 2 years, 7 months ago
  5. Download an image using requests, resize it using PIL, and save it to a model ImageField. by stewx 1 month ago

Comments

jpca (on April 4, 2015):

just changed field type

#image = models.ImageField(upload_to='images/%Y/%m', blank=True, null=True)
image = ResizedImageField(upload_to='images/%Y/%m', blank=True, null=True)

and worked ! :-)

I found an issue on PIL /pillow with debian side because au jpeg format, solved with:

sudo apt-get install libjpeg-dev
sudo pip install -I pillow

#

Please login first before commenting.