Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL open, save changes brightness of PNG

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

A cat before/after PIL

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?

like image 534
xjossy Avatar asked Dec 01 '25 23:12

xjossy


1 Answers

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)
like image 185
Martin Castin Avatar answered Dec 04 '25 15:12

Martin Castin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!