use*_*875 32 python python-imaging-library image-scaling pillow
假设我的图像是2322像素x 4128像素.如何缩放它以使宽度和高度都小于1028px?
我将无法使用Image.resize(https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize)因为这需要我给出新的宽度和高度.我打算做的是(下面的伪代码):
if (image.width or image.height) > 1028:
if image.width > image.height:
tn_image = image.scale(make width of image 1028)
# since the height is less than the width and I am scaling the image
# and making the width less than 1028px, the height will surely be
# less than 1028px
else: #image's height is greater than it's width
tn_image = image.scale(make height of image 1028)
Run Code Online (Sandbox Code Playgroud)
我猜我需要使用Image.thumbnail,但根据这个例子(http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails)和这个答案(如何使用PIL调整图像大小并保持其宽高比?),提供宽度和高度以创建缩略图.是否有任何功能可以采用新的宽度或新的高度(不是两者)并缩放整个图像?
fam*_*kin 62
Noo需要重新发明轮子,有Image.thumbnail可用的方法:
maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)
Run Code Online (Sandbox Code Playgroud)
确保最终尺寸不大于给定边界,同时保持纵横比.
指定PIL.Image.ANTIALIAS应用高质量的下采样滤波器以获得更好的调整大小结果,您可能也需要它.
Soh*_*a82 14
使用Image.resize,但同时计算宽度和高度.
if image.width > 1028 or image.height > 1028:
if image.height > image.width:
factor = 1028 / image.height
else:
factor = 1028 / image.width
tn_image = image.resize((int(image.width * factor), int(image.height * factor)))
Run Code Online (Sandbox Code Playgroud)