pythonpython-imaging-librarycolor-profile

How to preserve RGB color while saving png using PIL?


I've written a python program that combines three png images into a single image. I'm using PIL to open, resize, combine, and save the resulting image. All the functionality is there but the resulting image has a completely diferently color profile from the original.

I have tried several options:
1. I've attempted to create the new Image as "RGBA"
Result: Image no longer displayed by TKinter GUI
2. Attempted to copy the color profile from the original image then using that profile when saving the final image:
Code: profile = image.info.get("icc_profile", "") then I use the resulting variable when saving the file using the argument icc_profile = profile Result: No change

Minimal Reproducible Code

from PIL import Image as pImage
from tkinter.filedialog import asksaveasfilename

newImage = pImage.new('RGB', (976, 976))
background = pImage.open("Gameboy_Background.png")
screen_shot = pImage.open("screenshot.png")
cover_art = pImage.open("[coverart.png][1]")
newImage.paste(background)

w, h = screen_shot.size
newW = 875
newH = int(newW * h / w)
screen_shot = screen_shot.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(screen_shot, (50, 155))

w, h = cover_art.size
newW = 175
newH = int(newW * h / w)
cover_art = cover_art.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(cover_art, (100, 205))

file2Save = asksaveasfilename(initialdir="/", title="Select file", filetypes={("PNG files", "*.png")})
newImage.save(file2Save + ".png", "PNG")

PNG IMAGES USED
1: https://i.sstatic.net/Lj1wo.png [2]: https://i.sstatic.net/4iauQ.png [3]: https://i.sstatic.net/2voFC.png

Resulting Image


Solution

  • profile = image.info.get("icc_profile", "") then I use the resulting variable when saving the file using the argument icc_profile = profile

    That sounds like the right approach to me, actually. image is the screenshot image, right? That's the one whose profile you want to copy.

    from PIL import Image as pImage
    from tkinter.filedialog import asksaveasfilename
    
    newImage = pImage.new('RGB', (976, 976))
    background = pImage.open("Gameboy_Background.png")
    screen_shot = pImage.open("screenshot.png")
    cover_art = pImage.open("coverart.png")
    newImage.paste(background)
    
    profile = screen_shot.info.get("icc_profile", "")
    
    w, h = screen_shot.size
    newW = 875
    newH = int(newW * h / w)
    screen_shot = screen_shot.resize((newW, newH), pImage.ANTIALIAS)
    newImage.paste(screen_shot, (50, 155))
    
    w, h = cover_art.size
    newW = 175
    newH = int(newW * h / w)
    cover_art = cover_art.resize((newW, newH), pImage.ANTIALIAS)
    newImage.paste(cover_art, (100, 205))
    
    file2Save = "output"
    newImage.save(file2Save + ".png", "PNG", icc_profile=profile)
    

    Result:

    enter image description here