I'm using Pillow to open and save PNG image without any modifications. Images on output are displayed darker than the original:

Here is my code:
from PIL import Image
x = Image.open("cat.png")
x.save("cat-after.png","PNG")
If I open "cat-after.png", it will have same pixels as "cat.png".
I also noticed, that cat.png has altered gamma:
x.info
>> {'aspect': (1, 1),
>> 'chromaticity': (0.3127, 0.329, 0.64, 0.33, 0.3, 0.6, 0.15, 0.06),
>> 'gamma': 0.50994}
And in the reopened image, there is no metadata yet:
x2 = Image.open("cat-after.png")
x2.info
>> {}
And I think, this is because Pillow doesn't preserve gamma. How to make Pillow save the same image?
I encountered the same problem (with ffmpeg-generated PNGs) and I found a way to do this, although quite low-level. I got inspired by this github issue and this code.
from PIL import Image
from PIL import PngImagePlugin
x = Image.open("cat.png")
metadata = PngImagePlugin.PngInfo()
metadata.add(bytes("gAMA", "ascii"), round(x.info["gamma"] * 100_000).to_bytes(4, 'big'))
chromaticity_bytes = b""
for chrm in x.info["chromaticity"]:
chromaticity_bytes += round(chrm * 100_000).to_bytes(4, 'big')
metadata.add(bytes("cHRM", "ascii"), chromaticity_bytes)
x.save("cat-after.png", pnginfo=metadata)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With