Python中有很多图像处理库可以进行图像调整大小,其中PIL(Pillow)是一个非常流行的选择。以下是使用PIL库进行图像调整大小并保持纵横比的示例代码:
from PIL import Image
def resize_image_with_aspect_ratio(image_path, output_path, target_size):
# 打开图像
image = Image.open(image_path)
# 计算目标大小的纵横比
target_ratio = target_size[0] / target_size[1]
# 获取原始图像的宽度和高度
width, height = image.size
# 计算原始图像的纵横比
image_ratio = width / height
# 根据纵横比调整图像大小
if image_ratio > target_ratio:
# 原始图像更宽,则调整宽度到目标大小,高度按比例缩放
new_width = target_size[0]
new_height = int(new_width / image_ratio)
else:
# 原始图像更高,则调整高度到目标大小,宽度按比例缩放
new_height = target_size[1]
new_width = int(new_height * image_ratio)
# 调整图像大小
resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
# 保存调整大小后的图像
resized_image.save(output_path)
# 示例调用
image_path = 'input.jpg'
output_path = 'output.jpg'
target_size = (100, 100) # 目标大小 (宽度, 高度)
resize_image_with_aspect_ratio(image_path, output_path, target_size)
在上面的示例中,我们首先打开图像,然后计算目标大小和原始图像的纵横比。根据纵横比的比较结果,我们调整图像的宽度和高度,以保持纵横比不变。最后,我们使用resize()
函数调整图像大小,并使用save()
函数保存调整大小后的图像。