「アルファチャンネルはそのまま、でもRGBの透明部分には白を入れておきたい」

プログラム

import os
from PIL import Image

input_folder = r"Y:\INPUT"
output_folder = r"Y:\output"

os.makedirs(output_folder, exist_ok=True)

for filename in os.listdir(input_folder):
    if filename.lower().endswith(('.png', '.webp')):
        input_path = os.path.join(input_folder, filename)
        output_path = os.path.join(output_folder, filename)

        with Image.open(input_path).convert("RGBA") as img:
            # 分離
            r, g, b, a = img.split()

            # 白背景を作成
            white_bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
            # アルファを使って元画像を白背景に合成
            blended = Image.composite(img, white_bg, a)

            # アルファを元のまま戻す
            final_image = Image.merge("RGBA", (*blended.split()[:3], a))
            final_image.save(output_path)

print("RGBは白背景で、アルファはそのままにして保存")

Python

Posted by eightban