Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reduce the file size of a PNG image without changing its dimensions?

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?

like image 980
Ahsan Mukhtar Avatar asked Mar 05 '23 13:03

Ahsan Mukhtar


1 Answers

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

img_uncompressed: 691968 bytes

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

img_compressed: 406889 bytes

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).

like image 179
Florian Drawitsch Avatar answered May 12 '23 19:05

Florian Drawitsch