可以使用Pillow库中的Image类,结合裁剪和图像粘贴操作实现无需缩放的图像缩放。具体实现步骤如下:
1.读取原始图片,并获取其宽度和高度
2.定义目标图片宽度和高度,以及需要进行的缩放比例(目标宽度/原始宽度、目标高度/原始高度)
3.使用Image类的crop()方法对原始图片进行裁剪并且获取到目标宽度和高度的区域
4.将裁剪后的图片使用Image类的 resize() 方法进行缩放
5.定义一个目标图像的空图像,使用它的paste()方法将缩放后的图片粘贴到空图像的中央位置,使其与目标图像大小一致
6.保存输出的目标图片
具体代码如下:
from PIL import Image
#读取原始图片
orig_img = Image.open("example.jpg")
orig_width, orig_height = orig_img.size
#定义目标宽度、高度及缩放比例
target_width, target_height = 600, 400
scale_x, scale_y = target_width/orig_width, target_height/orig_height
#裁剪并缩放原始图片
crop_area = (int((orig_width-target_width)/(2*scale_x)), int((orig_height-target_height)/(2*scale_y)),
int((orig_width+target_width)/(2*scale_x)), int((orig_height+target_height)/(2*scale_y)))
crop_img = orig_img.crop(crop_area)
crop_width, crop_height = crop_img.size
resize_img = crop_img.resize((int(crop_width*scale_x), int(crop_height*scale_y))) #使用resize方法进行缩放
#粘贴到目标大小的空图像
out_img = Image.new("RGB", (target_width, target_height), (255, 255, 255))
out_img.paste(resize_img, ((target_width-crop_width)//2, (target_height-crop_height)//2))
#保存输出图片
out_img.save("output.jpg")
下一篇:不使用索引的指针和数组。