How to Compress an Image using a Python Program

Introduction

In this tutorial, you will learn how to compress or reduce image size without losing the quality of that image using a Python Program. We will use one of the most popular libraries called Pillow here to build the program. Since this is the only third-party library we will use, you have to install it if you didn't already.

👉Visit AlsoHack with Image: Extract Metadata from an Image using Python

Installation Process

👉Install Pillow: pip install Pillow

Look at the sample image below ("parrot.jpg"). Before compressing, the size is 222.5 kb. Let's see what happens after running the program.

This is an original image of a parrot which will be compressed using a python program.
parrot.jpg

Source Code

The entire program is pretty straightforward. I have added a single comment line before each line of the code. You will get the logic easily once you see it.


import os
from PIL import Image

# Enter the image path here
imagePath = "/home/suvankar/Desktop/parrot.jpg"

# Open the Image
img = Image.open(imagePath)

# Getting the width and height of the image
width, height = img.size

# Resizing the image with Anti Antialiasing technique
img = img.resize((width, height), Image.ANTIALIAS)

# os.path.basename: Extracting the filename from the file path
# os.path.splitext: Extracting the filename and extension separately
filename, extension = os.path.splitext(os.path.basename(imagePath))

# Setting the resulting filename
resultFilename = f"{filename}-compressed.jpg"

try:
# Convert the image to RGB mode
img = img.convert("RGB")
# Saving the image with the quality set to 80
# Attention: The lower quality number you select,
# the smaller the image size will be.
img.save(resultFilename, quality=80, optimize=True)
except Exception as es:
print(f"Error due to {es}")

Output

this is the compressed image of the original parrot image and it seems exactly the same as the original one.
parrot-compressed.jpg

The resulting image (parrot-compressed.jpg) seems exactly the same as the original one but the size has been reduced (124.6 kb).

There is a separate GUI Project on this topic, visit that also: Build an Image Compression App using Python Tkinter.

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post