Python Pillow 简明教程
Pillow - Resizing an Image
在 Pillow Library 中调整图像大小涉及更改图像的尺寸,即宽度和高度。此操作可用于使图像变大或变小,并且它可以满足多种目的,例如准备可在网站上显示的图像、减小文件大小或生成缩略图。
Resizing an image in Pillow Library involves changing the dimensions i.e. width and height of the image. This operation can be used to make an image larger or smaller and it can serve various purposes such as preparing images for display on a website, reducing file size or generating thumbnails.
Resizing an Image using the resize() method
在 Pillow 中, resize() 方法用于更改图像的尺寸。此函数允许我们通过以下方式调整图像大小。
In Pillow the resize() method is used to change the dimensions of an image. This function allows us to resize an image in the following ways.
-
Absolute Dimensions − We can specify the new width and height in pixels to which the image should be resized.
-
Maintaining Aspect Ratio − If We only specify one dimension either width or height then Pillow can automatically calculate the other dimension to maintain the image’s aspect ratio.
-
Scaling − We can resize the image by a scale factor which uniformly resizes both width and height while preserving the aspect ratio.
以下是 resize() 方法的基本语法 -
Here’s the basic syntax for the resize() method −
PIL.Image.resize(size, resample=3)
其中,
Where,
-
size − This can be either a tuple specifying the new width and height in pixels i.e. a single integer specifying the new size (width or height) or a float specifying a scaling factor.
-
resample(optional) − The default value is 3 which corresponds to the anti-aliased high-quality filter. We can choose from various resampling filters such as Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, Image.BICUBIC, Image.LANCZOS, etc.
以下是本章所有示例中使用的输入图像。
Following is the input image used in all the examples of this chapter.

Example
在这个示例中,我们使用 resize() 函数通过传递元组作为输入参数来调整图像的宽度和高度。
In this example we are using the resize() function for adjusting the width and height of the image by passing a tuple as input parameter.
from PIL import Image
#Open an image
image = Image.open("Images/rose.jpg")
#Resize to specific dimensions (e.g., 300x200 pixels)
new_size = (300, 200)
resized_image = image.resize(new_size)
#Display resized image
resized_image.show()

Example
在该示例中,我们保持原始输入图像的长宽比来调整图像大小。
Here in this example we are resizing the image by maintaining the same aspect ratio of the original input image.
from PIL import Image
#Open an image
image = Image.open("Images/rose.jpg")
#Resize by maintaining aspect ratio (e.g., specify the width)
new_width = 200
aspect_ratio_preserved = image.resize((new_width, int(image.height * (new_width / image.width))))
aspect_ratio_preserved.show()

Example
在这个示例中,我们按缩放因子调整图像的大孝。
In this example we are resizing the image with the scale by factor.
from PIL import Image
#Open an image
image = Image.open("Images/rose.jpg")
#Scale the image by a factor (e.g., 10% of the original size)
scaling_factor = 0.1
scaled_image = image.resize((int(image.width * scaling_factor), int(image.height * scaling_factor)))
scaled_image.show()
