python - PIL Image.resize() 不调整图片大小

标签 python resize python-imaging-library

我有一些奇怪的问题,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 像素。

最佳答案

resize() 返回调整大小的图像副本。它不会修改原件。正确的使用方法是:

from PIL import Image
#...

img = img.resize((150, newheight), Image.ANTIALIAS)

source

我认为您正在寻找的是 ImageOps.fit 函数。来自 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.

关于python - PIL Image.resize() 不调整图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252218/

相关文章:

python - Django South 忽略我的自定义规则

python - 如何在 for 循环内创建多个新数据框?

java - 在 GridLayout 布局管理器中动态调整链接到 JLabels 的图像大小

python - 使用 Python PIL 调整大小的图像较暗

java - gwt-查询 : resize event

python-3.x - PIL.ImageEnhance 增强颜色、亮度和对比度功能的公式是什么?

python - 在 Python 中使用 xml.etree.Elementtree 检索至少具有两个特定类型子代的所有元素

php - 一个 Web 框架,其中 AJAX 不是事后的想法

python - 在 python 中使用 pil 读取 tif 图像时出现值错误?

python - 如何循环保存PIL图像