from PIL import Image, ImageDraw from pathlib import Path def create_soft_edge_mask(width: int, height: int, transition_ratio: float = 0.02) -> Image: transition_height = int(height * transition_ratio) mask = Image.new("L", (width, height), 255) # 默认全白(不透明) draw = ImageDraw.Draw(mask) draw.rectangle([0, 0, width, height // 2 - transition_height // 2], fill=0) # 上半黑 draw.rectangle([0, height // 2 + transition_height // 2, width, height], fill=255) # 下半白 # 顶部和底部之间 2% 的区域渐变 for i in range(transition_height): alpha = int(255 * (i / transition_height)) y = height // 2 - transition_height // 2 + i draw.line([(0, y), (width, y)], fill=alpha) return mask def process_image(input_path: str | Path, output_path: str | Path): base_width, base_height = 800, 1000 original = Image.open(input_path).convert("RGBA") # 缩放图像宽度适配底图宽度 scale_ratio = base_width / original.width new_height = int(original.height * scale_ratio) resized = original.resize((base_width, new_height), Image.LANCZOS) # 创建底图并粘贴第一个图像(对齐顶部) base_image = Image.new("RGBA", (base_width, base_height), "white") base_image.paste(resized, (0, 0), resized) # 创建 A2 图层(对齐底部) A2 = resized.copy() A2_image = Image.new("RGBA", (base_width, base_height), (0, 0, 0, 0)) A2_y = base_height - A2.height A2_image.paste(A2, (0, A2_y), A2) # 创建遮罩并加为 alpha 通道 mask = create_soft_edge_mask(base_width, base_height, 0.02) A2_image.putalpha(mask) # 合成 final = Image.alpha_composite(base_image, A2_image) final.convert("RGB").save(output_path, format="PNG")