How to resize the new uploaded images using PIL before saving?

26,252

Solution 1

image = image.resize(size, Image.ANTIALIAS)

resize is non-destructive, it returns a new image.

Solution 2

I use django-resized for my projects.

Solution 3

I searched for a solution to resize uploaded photo before saving. There are a lot of info bit and bit here and there (in StackOverflow). Yet, no complete solution. Here is my final solution that I think works for people who wants it.

Development Highlight

  • Using Pillow for image processing (two packages required: libjpeg-dev, zlib1g-dev)
  • Using Model and ImageField as storage
  • Using HTTP POST or PUT with multipart/form
  • No need to save the file to disk manually.
  • Create multiple resolutions and stores their dimensions.
  • Did not modify the Model itself

Install Pillow

$ sudo apt-get install libjpeg-dev
$ sudo apt-get install zlib1g-dev
$ pip install -I Pillow

myapp/models.py

from django.db import models

class Post(models.Model):
    caption = models.CharField(max_length=100, default=None, blank=True)
    image_w = models.PositiveIntegerField(default=0)
    image_h = models.PositiveIntegerField(default=0)
    image = models.ImageField(upload_to='images/%Y/%m/%d/', default=None, 
                blank=True, width_field='image_w', height_field='image_h')
    thumbnail = models.ImageField(upload_to='images/%Y/%m/%d/', default=None,
                blank=True)

This model saves a photo with thumbnail and an optional caption. This should be similar to the real-world use case.

Our goal is to resize the photo to 640x640 and generate a 150x150 thumbnail. We also need to return the dimension of the photo in our web API. image_w and image_h is a cached dimension in table. Note that we need to add quota ' when we declare an ImageField. However, thumbnail does not need the width and height field (so you can see the different).

That's the model. We don't need to override or add any functions to the model.

myapp/serializers.py

We will use a ModelSerializer to process the incoming data from HTTP POST.

from rest_framework import serializers
from myapp.models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('caption',)

We do not want the serializer to handle the uploaded photo - we will do it ourself. So, no need to include 'image' in fields.

myapp/views.py

@api_view(['POST'])
@parser_classes((MultiPartParser,))
def handle_uploaded_image(request):
    # process images first.  if error, quit.
    if not 'uploaded_media' in request.FILES:
        return Response({'msg': 'Photo missing.'}, status.HTTP_400_BAD_REQUEST)
    try:
        im = Image.open(StringIO(request.FILES['uploaded_media'].read()))
    except IOError:
        return Response({'msg': 'Bad image.'}, status.HTTP_400_BAD_REQUEST)

    serializer = PostSerializer(data=request.DATA, files=request.FILES)
    if not serializer.is_valid():
        return Response({'msg': serializer.errors}, status.HTTP_400_BAD_REQUEST)

    post = Post.create()
    if serializer.data['caption'] is not None:
        post.caption = serializer.data['caption']

    filename = uuid.uuid4()
    name = '%s_0.jpg' % (filename)
    post.image.save(name=name, content=resize_image(im, 640))
    name = '%s_1.jpg' % (filename)
    post.thumbnail.save(name=name, content=resize_image(im, 150))

    post.save()
    return Response({'msg': 'success',
        'caption': post.caption,
        'image': {
            'url': request.build_absolute_uri(post.image.url),
            'width': post.image_w,
            'height': post.image_h,
        }
        'thumbnail': request.build_absolute_uri(post.thumbnail.url),
    }, status.HTTP_201_CREATED)

helper functions in a shared py

def resize_image(im, edge):
    (width, height) = im.size
    (width, height) = scale_dimension(w, h, long_edge=edge)
    content = StringIO()
    im.resize((width, height), Image.ANTIALIAS).save(fp=content, format='JPEG', dpi=[72, 72])
    return ContentFile(content.getvalue())

def scale_dimension(width, height, long_edge):
    if width > height:
        ratio = long_edge * 1. / width
    else:
        ratio = long_edge * 1. / height
    return int(width * ratio), int(height * ratio)

Here, we do not use Image.thumbnail because it will change the original image. This code is suitable if we want to store multiple resolutions (such as low res and high res for different purpose). I found that resizing the incoming message twice will degrade the quality.

We also do not save the image directly to disk. We push the image via a ContentFile (a File object for content in memory) to ImageField and let the ImageField do its job. We wants the multiple copies of image have the same file name with different postfix.

Credits

Here are the links of codes that I had references to build this solution:

If you want to validate the image as well, see this: https://stackoverflow.com/a/20762344/3731039

Solution 4

here is what worked for me, inspired a little from django-resized

@receiver(pre_save, sender=MyUser)
@receiver(pre_save, sender=Gruppo)
def ridimensiona_immagine(sender, instance=None, created=False, **kwargs):
    foto = instance.foto

    foto.file.seek(0)
    thumb = PIL.Image.open(foto.file)
    thumb.thumbnail((
        200, 
        200
        ), PIL.Image.ANTIALIAS)


    buffer = StringIO.StringIO()
    thumb.save(buffer, "PNG")
    image_file = InMemoryUploadedFile(buffer, None, 'test.png', 'image/png', buffer.len, None)

    instance.foto.file = image_file
Share:
26,252
beni
Author by

beni

I'm an Android Developer

Updated on August 01, 2021

Comments

  • beni
    beni almost 3 years

    I want to resize the new images in a height and width of 800px and save them. And the app mustn't store the real image. Any help?

    This is my code, it saves the original image and don't the resized photo:

    models.py:

    class Photo(models.Model):        
        photo = models.ImageField(upload_to='photos/default/')
    
    
        def save(self):
    
            if not self.id and not self.photo:
                return            
    
            super(Photo, self).save()
    
            image = Image.open(self.photo)
            (width, height) = image.size
    
            "Max width and height 800"        
            if (800 / width < 800 / height):
                factor = 800 / height
            else:
                factor = 800 / width
    
            size = ( width / factor, height / factor)
            image.resize(size, Image.ANTIALIAS)
            image.save(self.photo.path)
    
  • beni
    beni over 12 years
    I know, but how I save the resized photo without saving the original?
  • wmil
    wmil over 12 years
    replace the line "image.resize(size, Image.ANTIALIAS)" with "image = image.resize(size, Image.ANTIALIAS)" Right now you're resizing but ignoring the result and saving the original image.
  • kungphu
    kungphu about 11 years
    +1 because this project works perfectly out of the box with django-storages+boto. Excellent, saved me a lot of headaches!
  • max4ever
    max4ever almost 10 years
    this project didn't work out of the box with django storages + boto, broke file upload for me from the api
  • Ali Rasim Kocal
    Ali Rasim Kocal almost 9 years
    Using // may be a better option though, as the rest of the code may assume division results will be float.
  • Paul Bormans
    Paul Bormans almost 8 years
    I liked it as well; since the project is so small actually i just copied the form class and used it...
  • Simon Steinberger
    Simon Steinberger over 6 years
    This seems to be completely off topic :-/