在使用Python进行图像处理时,可以使用PIL库(Python Imaging Library)来实现保持图像中心并填充边缘的白色边框,增加图像大小的功能。下面是一个示例代码:
from PIL import Image, ImageOps
def add_white_border(image_path, target_size):
# 打开图像
image = Image.open(image_path)
# 计算目标尺寸和当前尺寸的差异
width_diff = target_size[0] - image.width
height_diff = target_size[1] - image.height
# 计算要填充的边框大小
left = width_diff // 2
right = width_diff - left
top = height_diff // 2
bottom = height_diff - top
# 使用ImageOps模块中的pad函数添加边框
bordered_image = ImageOps.pad(image, (image.width + left + right, image.height + top + bottom), color=(255, 255, 255))
# 返回添加边框后的图像
return bordered_image
# 示例用法
image_path = 'example.jpg' # 图像文件路径
target_size = (800, 600) # 目标尺寸
bordered_image = add_white_border(image_path, target_size)
bordered_image.show() # 显示添加边框后的图像
在上述代码中,add_white_border函数接受一个图像文件路径和目标尺寸作为参数。它使用PIL库中的Image.open函数打开图像文件,然后计算目标尺寸和当前图像尺寸的差异。接下来,它使用ImageOps.pad函数在图像的四周填充白色边框,最后返回添加边框后的图像对象。
使用示例中的代码,可以将指定图像文件添加白色边框并调整大小为目标尺寸,并通过show方法显示添加边框后的图像。你可以根据自己的需求修改代码中的路径和目标尺寸。