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

 ################################################################################################ # name: 05_compress_image_01.py # desc: Compress image file using python # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw, ImageFont import os print('*** Program Started ***') image_font_path = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' # image_name_input = '05_compress_image_01_input.png' image_name_input = '05_compress_image_01_input.jpg' im = Image.open(image_path_input + image_name_input) print('Input file size : ', im.size ) print('Input file name : ', image_name_input ) print('Input Image Size : ', os.path.getsize (image_path_input + image_name_input)) # image_name_output = '05_compress_image_01_output.png' image_name_output = '05_compress_image_01_output.jpg' im.save(image_path_output + image_name_output ,optimize=True,quality=50) print('Output file size : ', im.size ) print('Output file name : ', image_name_output) print('Output Image Size : ', os.path.getsize (image_path_output + image_name_output)) print('*** Program Ended ***')

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.

## 2 Replies to “How to compress images using Python”

1. Abhi says:

Sir i am in very big problem sir please help me that i wanted to compress images using pillow and i wanted that the image take his original width and height and then resize