You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python批量为透明PNG添加白色背景并调整尺寸?

批量处理透明PNG:添加白色背景并调整尺寸

首先,你需要安装Pillow库,这是Python处理图片的常用工具:

pip install pillow

以下是批量处理透明PNG的完整脚本,它会帮你给图片添加白色背景并调整尺寸:

from pathlib import Path
from PIL import Image

# 配置参数,按需修改
INPUT_FOLDER = r'C:\test\images'  # 透明PNG所在文件夹
OUTPUT_FOLDER = r'C:\test\processed_images'  # 处理后图片的保存路径
TARGET_SIZE = (800, 800)  # 目标尺寸,比如(800,800)
BACKGROUND_COLOR = (255, 255, 255)  # 白色背景的RGB值

# 创建输出文件夹(不存在则自动生成)
Path(OUTPUT_FOLDER).mkdir(exist_ok=True)

# 遍历文件夹里的所有透明PNG(这里匹配你用rembg生成的.out.png)
for png_file in Path(INPUT_FOLDER).glob('*.out.png'):
    # 打开透明PNG图片
    with Image.open(png_file) as img:
        # 创建目标尺寸的白色背景图(RGB模式,无透明通道)
        background = Image.new('RGB', TARGET_SIZE, BACKGROUND_COLOR)
        
        # 把原图按比例缩放到不超过目标尺寸(避免变形)
        img.thumbnail(TARGET_SIZE)
        
        # 计算居中粘贴的偏移量(如果不需要居中,直接用(0,0)即可)
        offset = ((TARGET_SIZE[0] - img.width) // 2, (TARGET_SIZE[1] - img.height) // 2)
        
        # 将透明图粘贴到背景上,用原图的alpha通道作为蒙版,保留非透明区域
        background.paste(img, offset, img)
        
        # 保存处理后的图片,可选择jpg/png格式
        output_filename = f"{png_file.stem}_processed.jpg"
        output_path = Path(OUTPUT_FOLDER) / output_filename
        background.save(output_path, quality=95)

print("批量处理完成!")

关键代码说明

  • 路径与参数配置:直接修改INPUT_FOLDER、TARGET_SIZE等参数即可适配你的需求
  • 遍历文件:glob('*.out.png')精准匹配rembg生成的透明图,要处理所有PNG的话改成*.png
  • 背景添加:通过Image.new创建白色背景,再用paste方法结合原图的alpha通道,实现透明区域填充白色
  • 尺寸调整:thumbnail方法会按原图比例缩放,避免拉伸变形;如果需要强制拉伸到目标尺寸,改用img.resize(TARGET_SIZE)即可

可选:合并去背景与后续处理

如果你想把rembg去背景、加白色背景、调整尺寸整合为一个脚本,可以用下面的代码:

import rembg
from pathlib import Path
from rembg import remove, new_session
from PIL import Image

# 配置参数
INPUT_FOLDER = r'C:\test\images'
TEMP_PNG_FOLDER = r'C:\test\temp_png'  # 临时存去背景后的PNG
OUTPUT_FOLDER = r'C:\test\processed_images'
TARGET_SIZE = (800, 800)
BACKGROUND_COLOR = (255, 255, 255)

# 创建所需文件夹
Path(TEMP_PNG_FOLDER).mkdir(exist_ok=True)
Path(OUTPUT_FOLDER).mkdir(exist_ok=True)

# 第一步:批量给JPG去背景
session = new_session()
for jpg_file in Path(INPUT_FOLDER).glob('*.jpg'):
    input_path = str(jpg_file)
    output_path = str(Path(TEMP_PNG_FOLDER) / f"{jpg_file.stem}.out.png")
    
    with open(input_path, 'rb') as i, open(output_path, 'wb') as o:
        input_data = i.read()
        output_data = remove(input_data, session=session)
        o.write(output_data)

# 第二步:批量处理透明PNG
for png_file in Path(TEMP_PNG_FOLDER).glob('*.out.png'):
    with Image.open(png_file) as img:
        background = Image.new('RGB', TARGET_SIZE, BACKGROUND_COLOR)
        img.thumbnail(TARGET_SIZE)
        offset = ((TARGET_SIZE[0] - img.width) // 2, (TARGET_SIZE[1] - img.height) // 2)
        background.paste(img, offset, img)
        
        output_filename = f"{png_file.stem}_processed.jpg"
        output_path = Path(OUTPUT_FOLDER) / output_filename
        background.save(output_path, quality=95)

print("全流程处理完成!")

内容的提问来源于stack exchange,提问作者Deidraak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:20:33