How to compress images using Python

Python Library Pillow can be used very effectively to compress images. While doing some research on this I found that .JPG files can be compress very effectively however this does not work well with .PNG files. Here is sample program to reduce file size of an image.

Output of the program while using .JPG file as input and output

$ python3.6 05_compress_image_01.py 
*** Program Started ***
Input file size : (5456, 3632)
Input file name : 05_compress_image_01_input.jpg
Input Image Size : 1611664
Output file size : (5456, 3632)
Output file name : 05_compress_image_01_output.jpg
Output Image Size : 443479
*** Program Ended ***

Output of the program while using .PNG files as input and output

$ python3.6 05_compress_image_01.py 
*** Program Started ***
Input file size : (1920, 1282)
Input file name : 05_compress_image_01_input.png
Input Image Size : 3683320
Output file size : (1920, 1282)
Output file name : 05_compress_image_01_output.png
Output Image Size : 3619363
*** Program Ended ***

As you can see, while using .PNG files for input and output, there is hardly any change in file size however when you used .JPG files, output files is of 27% of original file size. Your percentage reduction might be different based on the file that you have used.

Please note input and out file dimensions, number of pixels stays the same.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.