leemengtaiwan
10/10/2017 - 9:02 AM

刪除png圖片的alpha channel並存成jpg

刪除png圖片的alpha channel並存成jpg

# References
# https://stackoverflow.com/questions/9166400/convert-rgba-png-to-rgb-with-pil

from PIL import Image

def get_rgb_image(file_path, delete_original_image=True):
    """
    Remove image's alpha channel and return the path of the
    transformed image

    Parameters
    ----------
    file_path: str
        relative path to the image with alpha channel
    delete_original_image: bool
        set to true to remove original image after transformation

    Returns
    -------
    transformed_file_path; str
        relative path to the image without alpha channel
    """
    png = Image.open(file_path)
    png.load()  # required for png.split()

    background = Image.new("RGB", png.size, (255, 255, 255))
    background.paste(png, mask=png.split()[3])  # 3 is the alpha channel

    transformed_file_path = file_path.replace('.png', '.jpg')
    background.save(transformed_file_path, 'JPEG', quality=80)

    # delete original image

    return transformed_file_path