简体   繁体   中英

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.

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.

[Update] ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.image.resize((100,100),Image.ANTIALIAS)

Today you should use something like this:

from PIL import Image

img = Image.open(r"C:\test.png")
img.show()
img_resized = img.resize((100, 100), Image.Resampling.LANCZOS)
img_resized.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM