我有一些奇怪的问题,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)
我认为您正在寻找的是 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/