如何使用 PIL 调整图像大小并保持其纵横比?
Image.open()
Image.resize()
下面是一个 Python 代码示例,演示如何
from PIL import Image def resize_image(input_image_path, output_image_path, size): # Open the image file with Image.open(input_image_path) as img: # Calculate aspect ratio width_percent = (size / width_percent = ( float(img.size[0])) height_size = height_size = i int((float(img.size[1]) * float(width_percent))) # Resize the image with preserving aspect ratio img = img.resize((size, height_size), Image.ANTIALIAS) img = img.resize((size, height_size), Image.ANTIALI img = img. # Save or show the image img.save(output_image_path) img.show() img.save(output_ # Example usage: input_image = 'input_image.jpg' output_image = output_imag 'resized_image.jpg' new_size = new 300 resize_image(input_image, output_image, new_size) resize_image(input_image, output_image resize_image(
打开图像:Image.oImage.open(input_image_path)打开图片input_image_path`。
Image.o
打开图片
计算新尺寸
:
size
img.size[0]
使用此比率计算新的高度(height_size)维持
height_size
调整图像大小:img.resimg.resize((size, height_size), Image.ANTIALIAS)调整 t 的大小
img.resize((size, height_size), Image.ANTIALIAS)
保存或显示:iimg.save(output_image_path)在output_image_path。 选项img.show()`显示
i
在
。 选项
new_size
Image.ANTIALIAS
img.resize()
pip install Pillow
这种方法可确保调整图像大小的同时保持其纵横比,防止失真并保持图像质量