Python / Pillow:如何缩放图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24745857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python / Pillow: How to scale an image
提问by user2719875
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?
假设我有一个 2322px x 4128px 的图像。如何缩放它以使宽度和高度都小于 1028 像素?
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):
我将无法使用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)
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?
我猜我需要使用Image.thumbnail
,但根据这个例子(http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails)和这个答案(How do I resize an image using PIL并保持其纵横比?),提供宽度和高度以创建缩略图。是否有任何函数采用新宽度或新高度(不是两者)并缩放整个图像?
采纳答案by famousgarkin
Noo need to reinvent the wheel, there is the Image.thumbnail
method available for this:
不需要重新发明轮子,有Image.thumbnail
可用的方法:
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.
确保生成的大小不大于给定的边界,同时保持纵横比。
Specifying PIL.Image.ANTIALIAS
applies a high-quality downsampling filter for better resize result, you probably want that too.
指定PIL.Image.ANTIALIAS
应用高质量的下采样过滤器以获得更好的调整大小结果,您可能也想要。
回答by Sohcahtoa82
Use Image.resize, but calculate both width and height.
使用 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)))