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 Also: Hack 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.
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
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.