import os
from PIL import Image
from rembg import remove
from io import BytesIO
current_dir = os.path.dirname(os.path.abspath(__file__))
output_dir = os.path.join(current_dir, "output")
os.makedirs(output_dir, exist_ok=True)
TARGET_SIZE = (800, 800)
PADDING = 0.90 # 商品占据画布的比例(0.90 表示留 10% 的边距,商品主体更大更突出)
for filename in os.listdir(current_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
img_path = os.path.join(current_dir, filename)
print(f"正在处理: {filename} ...")
# 1. 扣除背景
with open(img_path, 'rb') as f:
no_bg_bytes = remove(f.read())
img_no_bg = Image.open(BytesIO(no_bg_bytes)).convert("RGBA")
# 2. 关键步骤:自动裁剪掉周围所有透明空白,只保留商品本体边界
bbox = img_no_bg.getbbox()
if bbox:
img_no_bg = img_no_bg.crop(bbox) # 紧贴商品边缘剪裁
# 3. 计算等比例放大尺寸(让商品占满画布的 90%)
max_target_w = int(TARGET_SIZE[0] * PADDING)
max_target_h = int(TARGET_SIZE[1] * PADDING)
img_w, img_h = img_no_bg.size
ratio = min(max_target_w / img_w, max_target_h / img_h)
new_w = int(img_w * ratio)
new_h = int(img_h * ratio)
# 4. 放大商品主体(保证高画质)
img_resized = img_no_bg.resize((new_w, new_h), Image.Resampling.LANCZOS)
# 5. 创建 800x800 纯白画布并将放大后的商品居中
white_bg = Image.new("RGBA", TARGET_SIZE, (255, 255, 255, 255))
x_offset = (TARGET_SIZE[0] - new_w) // 2
y_offset = (TARGET_SIZE[1] - new_h) // 2
white_bg.paste(img_resized, (x_offset, y_offset), img_resized)
# 6. 保存导出
final_img = white_bg.convert("RGB")
save_path = os.path.join(output_dir, os.path.splitext(filename)[0] + "_800x800.jpg")
final_img.save(save_path, quality=95)
print(f"成功导出大主体 800x800 图: {filename}")
print("\n全部处理完成!")