以下是一个示例代码,演示如何按比例裁剪图像:
from PIL import Image
def crop_image(image_path, output_path, aspect_ratio):
# 打开图像
image = Image.open(image_path)
# 获取原始图像的尺寸
width, height = image.size
# 计算目标图像的尺寸
target_width = int(width * aspect_ratio)
target_height = int(height * aspect_ratio)
# 计算裁剪区域的左上角和右下角坐标
left = int((width - target_width) / 2)
upper = int((height - target_height) / 2)
right = left + target_width
lower = upper + target_height
# 裁剪图像
cropped_image = image.crop((left, upper, right, lower))
# 保存裁剪后的图像
cropped_image.save(output_path)
# 示例用法
input_path = "input.jpg"
output_path = "output.jpg"
aspect_ratio = 0.5 # 裁剪比例为50%
crop_image(input_path, output_path, aspect_ratio)
在这个示例中,首先使用PIL库中的Image.open()函数打开图像。然后,获取原始图像的尺寸,并根据给定的比例计算裁剪后图像的尺寸。接下来,计算裁剪区域的左上角和右下角坐标。最后,使用crop()函数裁剪图像,并使用save()函数保存裁剪后的图像。