Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 464
beni Avatar asked Nov 01 '11 17:11

beni


People also ask

How do I resize an image without losing content?

If you want to resize an image without losing quality, you need to make sure that the "Resample" checkbox is unchecked. This checkbox tells Paint to change the number of pixels in the image. When you uncheck this box, Paint will not change the number of pixels, and the quality of the image will not be reduced.

How do I resize a saved image?

Right-click on the image you want to resize, then select Edit. Click Resize. Set the percentage or how many pixels you want to resize your image by. Then click OK.


2 Answers

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

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

like image 89
wmil Avatar answered Oct 23 '22 13:10

wmil


I use django-resized for my projects.

like image 39
un1t Avatar answered Oct 23 '22 15:10

un1t