PIL Image.resize() 未调整图片大小
我有一些奇怪的问题,PIL 没有调整图像大小。
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')
此代码运行时没有任何错误,并在正确的文件夹中生成名为 mugshotv2.jpg
的图像,但它不会调整其大小。 它做了一些事情,因为图片的大小从 120 kb 下降到 20 kb,但尺寸保持不变。
也许您还可以建议用更少的代码将图像裁剪成正方形的方法。 我有点以为 Image.thumbnail
可以做到这一点,但它所做的是将我的图像按宽度缩放到 150 像素,高度保留 100 像素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
今天你应该使用这样的东西:
Today you should use something like this:
[更新]
ANTIALIAS 已弃用,并将在 Pillow 10 (2023-07-01) 中删除。 使用 Resampling.LANCZOS 代替.image.resize((100,100),Image.ANTIALIAS)
[Update]
ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.LANCZOS instead.image.resize((100,100),Image.ANTIALIAS)
resize()
返回已调整大小的图像副本。 它不会修改原始内容。 正确的使用方法是:source
我认为您正在寻找的是 ImageOps.fit功能。 来自 PIL 文档:
resize()
returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:source
I think what you are looking for is the ImageOps.fit function. From PIL docs: