Python/枕头:如何缩放图像 [英] Python / Pillow: How to scale an image
问题描述
假设我有一个2322px x 4128px的图像.如何缩放比例,以使宽度和高度都小于1028px?
Suppose I have an image which is 2322px x 4128px. How do I scale it so that both the width and height are both less than 1028px?
我将无法使用Image.resize
( https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize ),因为这需要我同时指定新的宽度和高度.我打算做的是(下面的伪代码):
I won't be able to use Image.resize
(https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize) since that requires me to give both the new width and height. What I plan to do is (pseudo code below):
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)
我猜我需要使用Image.thumbnail
,但是根据此示例( http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails )和此答案(
I am guessing I need to use Image.thumbnail
, but according to this example (http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails) and this answer (How do I resize an image using PIL and maintain its aspect ratio?), both the width and the height are provided in order to create the thumbnail. Is there any function which takes either the new width or the new height (not both) and scales the entire image?
推荐答案
Noo need to reinvent the wheel, there is the Image.thumbnail
method available for this:
maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)
确保结果尺寸不超过给定范围,同时保持宽高比.
Ensures the resulting size is not bigger than the given bounds while maintains the aspect ratio.
指定PIL.Image.ANTIALIAS
应用高质量的下采样滤波器以获得更好的调整大小结果,
Specifying PIL.Image.ANTIALIAS
applies a high-quality downsampling filter for better resize result, you probably want that too.
这篇关于Python/枕头:如何缩放图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!