当使用Image.resize()
方法调整图像尺寸时,如果原始图像的宽高比与目标尺寸的宽高比不匹配,可能会导致调整后的图像在长宽上不一致。这是因为默认情况下,Image.resize()
方法会保持原始图像的宽高比。
要确保调整后的图像具有一致的长宽比,请使用参数resample=Image.ANTIALIAS
进行抗锯齿处理,并指定目标尺寸的长宽比。示例如下:
from PIL import Image
image = Image.open("example.jpg")
target_width = 800
target_height = 600
# 计算目标尺寸的长宽比
target_ratio = target_width / target_height
# 调整图像尺寸并保持长宽比一致
resized_image = image.resize((target_width, int(target_width / target_ratio)), resample=Image.ANTIALIAS)
# 检查调整后的图像大小
print(resized_image.size)
通过指定合适的目标尺寸和长宽比,可以确保调整后的图像在大小和长宽上保持一致。
内容由零声教学AI助手提供,问题来源于学员提问