如何使用Python为不同尺寸图像添加padding,实现统一尺寸与均等边框
图像处理实现方案
实现逻辑
- 先裁剪掉所有PNG自带的空白/透明边框,提取有效内容区域
- 对提取到的内容做等比缩放,保证不会拉伸变形,且不超过预留的内容区域大小
- 把缩放后的内容居中粘贴到100×100的透明画布上,自动生成均匀的四周边框
完整代码
from PIL import Image from glob import glob # 可自定义配置 TARGET_SIZE = (100, 100) BORDER_SIZE = 4 # 四周统一边框宽度,单位像素 BACKGROUND = (0, 0, 0, 0) # 输出图像背景,默认透明,白色背景可改为(255,255,255,255) images = glob('src/assets/emotes/medals/**/*.png', recursive=True) for img_path in images: with Image.open(img_path).convert('RGBA') as im: # 裁剪原图自带的空白/透明边框 content_bbox = im.getbbox() # 处理全透明的极端情况 content_im = im.crop(content_bbox) if content_bbox else im # 计算等比缩放比例,适配内容区域 content_max_width = TARGET_SIZE[0] - 2 * BORDER_SIZE content_max_height = TARGET_SIZE[1] - 2 * BORDER_SIZE scale_ratio = min(content_max_width / content_im.width, content_max_height / content_im.height) scaled_width = int(content_im.width * scale_ratio) scaled_height = int(content_im.height * scale_ratio) # 高质量缩放,支持放大缩小 scaled_content = content_im.resize((scaled_width, scaled_height), Image.Resampling.LANCZOS) # 居中粘贴生成最终图 output_im = Image.new('RGBA', TARGET_SIZE, BACKGROUND) paste_x = (TARGET_SIZE[0] - scaled_width) // 2 paste_y = (TARGET_SIZE[1] - scaled_height) // 2 output_im.paste(scaled_content, (paste_x, paste_y), mask=scaled_content) output_im.save(img_path)
特殊场景适配
如果你的图像自带的是白色非透明边框,在裁剪前加入以下代码即可自动识别白色边框并裁剪:
import numpy as np # 放在im = Image.open(img_path).convert('RGBA')之后 img_data = np.array(im) # 识别纯白色区域,转为透明 white_area = (img_data[..., :3] == [255, 255, 255]).all(axis=-1) img_data[white_area, 3] = 0 im = Image.fromarray(img_data)
内容的提问来源于stack exchange,提问作者developing
相关产品推荐
相关产品推荐

