I want to reduce the file size of a PNG file using Python. I have gone through a lot of material on the internet, but I could not find anything where I would reduce the file size for an image without changing the dimensions i.e. height/width. What I have found is how to change the dimensions of the image, using PIL or some other library of Python.
How can I reduce image file size while keeping it's dimensions constant?
PNG is a lossless format but it still can be compressed in a lossless fashion. Pillow's Image class comes with a png writer accepting a compress_level
parameter.
It can easily be demonstrated that it works:
Step 1: Load generic rgb lena image in .png format:
import os
import requests
from PIL import Image
from io import BytesIO
img_url = 'http://pngnq.sourceforge.net/testimages/lena.png'
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
Step 2: Write png with compress_level=0
:
path_uncompressed = './lena_uncompressed.png'
img.save(path_uncompressed,compress_level=0)
print(os.path.getsize(path_uncompressed))
> 691968
Step 3: Write png with compress_level=9
:
path_compressed = './lena_compressed.png'
img.save(path_compressed,compress_level=9)
print(os.path.getsize(path_compressed))
> 406889
which in this case gives us a respectable 30% compression without any obvious image quality degradation (which should be expected for a lossless compression algorithm).
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