`from PIL import Image, ImageOps, ImageFilter
import os
def add_border_to_image(image_path, output_path, border_size=2):
# 打开图片
image = Image.open(image_path)
# 确保图片是RGBA模式(带有透明通道)
if image.mode != 'RGBA':
image = image.convert('RGBA')
# 创建一个滤镜,用于找到边缘
mask = image.split()[-1] # 获取透明通道作为mask
edge_mask = mask.filter(ImageFilter.FIND_EDGES)
dilated_mask = edge_mask.filter(ImageFilter.MaxFilter(size=border_size * 2 + 1)) # 扩大边缘区域
# 创建一个全透明的背景图片
border_image = Image.new('RGBA', image.size, (0, 0, 0, 0))
# 在边缘区域应用白色
border = Image.new('RGBA', image.size, (255, 255, 255, 255))
border_image.paste(border, mask=dilated_mask)
# 将原始图片粘贴到带有白色边缘的背景上
final_image = Image.alpha_composite(border_image, image)
# 保存图片
final_image.save(output_path)
使用方法
for root, dirs, files in os.walk('.'):
for file in files:
# 检查文件的扩展名
filename, ext = os.path.splitext(file)
if ext.lower() == '.png':
# 如果文件是PNG图片,那么给它添加描边
input_image_path = os.path.join(root, file)
output_image_path = os.path.join(root, filename + '_border' + ext)
add_border_to_image(input_image_path, output_image_path, 2)
`