Search code examples
pythonimage-processingpython-imaging-librarypng

How crop/blur a .png using python-pillow, wihtout changing anything else


I've found several helpful posts on here explain how to crop an image with the Pillow library for Python, but cropping a .png with pillow distorts the colors and darkens the picture a bit. I'm using .png because I want to avoid the images getting distorted in processing.

When I run a dummy script that doesn't even do any cropping:

from PIL import Image

with Image.open('test.png') as image:
    image.save('test copy.png')

The resulting copy is ~30% smaller in file size than the original and noticeably darker, if you flip between them in a photo viewer. How do I get Pillow to crop a picture but leave the colors alone? I'd also like to do the same with local blur (for anonymization), apply a blur in one area without altering the rest of the image.

EDIT: Uploaded .png file and discolored copies to https://github.com/Densaugeo/stack-overflow-question/tree/main


Solution

  • Kudos, and upvotes to @MarkAdler for sleuthing the lack of gAMA chunk. Here is a method of propagating forward the gAMA from one file to another using exiftool:

    exiftool -tagsfromfile goodImage.png -gamma brokenImage.png
    

    You can probably do this in Python, by adapting this answer.


    Here is another method using pngcheck and pngcrush.