Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL Image.resize() not resizing the picture

I have some strange problem with PIL not resizing the image.

from PIL import Image img = Image.open('foo.jpg')  width, height = img.size ratio = floor(height / width) newheight = ratio * 150  img.resize((150, newheight), Image.ANTIALIAS)  img.save('mugshotv2.jpg', format='JPEG') 

This code runs without any errors and produces me image named mugshotv2.jpg in correct folder, but it does not resize it. It does something to it, because the size of the picture drops from 120 kb to 20 kb, but the dimensions remain the same.

Perhaps you can also suggest way to crop images into squares with less code. I kinda thought that Image.thumbnail does it, but what it did was that it scaled my image to 150 px by its width, leaving height 100px.

like image 372
Odif Yltsaeb Avatar asked Aug 09 '09 20:08

Odif Yltsaeb


People also ask

How do I resize an image using PIL and maintain its aspect ratio?

To resize an image using PIL and maintain its aspect ratio with Python, we can open the image with Image. open . Then we calculate the new width and height to scale the image to according to the new width. And then we resize the image with the resize method and save the new image with the save method.

How do I resize an image without cropping in Python?

just pass the image and mention the size of square you want. explanation: function takes input of any size and it creates a squared shape blank image of size image's height or width whichever is bigger. it then places the original image at the center of the blank image.


1 Answers

resize() returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:

from PIL import Image #...  img = img.resize((150, newheight), Image.ANTIALIAS) 

source

I think what you are looking for is the ImageOps.fit function. From PIL docs:

ImageOps.fit(image, size, method, bleed, centering) => image

Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. The size argument is the requested output size in pixels, given as a (width, height) tuple.

like image 155
Nadia Alramli Avatar answered Sep 17 '22 14:09

Nadia Alramli