Introduction
You may have noticed that some online admission or application portals require photos to be smaller than a certain size to upload. There are many online tools available offers to compress images (by reducing the image size). Here, in this lesson, we will build such a tool which is an Image Compressor Application in Python. It will help you to reduce the size of any image without losing the quality and save the resulting image.
One of the interesting things about this Image Compressor is, you can choose the reducing quality of the image as per your choice here. The application offers a drop-down list widget to select the result image quality. The lower the number you select, the smaller the image size will be.
While creating this lovely project, you will also learn how image compression can be done using python. It's a GUI project where the Tkinter library plays a major role; side by side the Pillow library is used here to reduce the image sizes. The entire journey is pretty straightforward, just stay tuned until the end, you can successfully launch this Python Image Compressor Project in your system. Let's see, what you have required to build this project.
👉Visit Also: Image to Pencil Sketch Converter in Python - Tkinter Project
Requirements
In this Image Compression Project, two third-party libraries play a major role, so you must install them if you didn't already.
👉Install Tkinter: pip install Tk
👉Install Pillow: pip install Pillow
How to use this Application?
The User Interface of this App is very simple (See the image below). So it's very easy to use. Just follow these three steps below.
User Interface of the App |
Step 1. Press the Select Button to choose the image,
Step 2. Select the resulting image quality,
Step 3. Press the "Compress Image" Button,
Step 4. Choose the "Save To" path to select the folder where the compressed image will be stored.
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
import PIL.Image
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
# The Compressor class
class Compressor:
def __init__(self, root):
self.window = root
self.window.geometry("520x320")
self.window.title("Image Compressor")
self.window.configure(bg="white")
self.window.resizable(width = False, height = False)
# Setting the image path Null initially
self.imagePath = ''
headingLabel = Label(self.window, text="Image Compressor", \
font=("Kokila", 18, "bold"), bg="white")
headingLabel.place(x=130, y=30)
# Button to select the Image through the filedialog widget
selectButton = Button(self.window, text="Select Image", \
font=("Helvetica", 10), bg="green", fg="white",command=self.Open_Image)
selectButton.place(x=120, y=110)
imageQuality = Label(self.window, text="Image Quality", \
font=("Times New Roman", 12), bg="white")
imageQuality.place(x=245, y=110)
# The list of the image quality (which will be saved)
imageQualityList = [10, 20, 30, 40, 50, 60, 70, 80]
self.clicked = StringVar()
self.clicked.set(80)
# Drop down widget to show the image quality options
qualityMenu = OptionMenu(self.window, self.clicked,*imageQualityList)
qualityMenu.config(width=2, font=("Helvetica", 9, "bold"), \
bg="gray50", fg="white")
qualityMenu.place(x=345, y=109)
# Button to compress the selected image
compressButton = Button(self.window, text="Compress Image", \
font=("Helvetica", 10), bg="yellow", fg="black", \
command=self.Compress_Image)
compressButton.place(x=190, y=160)
# The frame to show the selected image path
self.frame = Frame(self.window, bg="white", width=520, height=100)
self.frame.place(x=0, y=200)
# Open an Image through the filedialog widget
def Open_Image(self):
# Select the image and store the path through the Tkinter
# filedialog widget
self.imagePath = \
filedialog.askopenfilename(initialdir = "/", \
title = "Select an Image", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
# If an image is chosen, this logic will be satisfied
if len(self.imagePath) != 0:
imagePathLabel = Label(self.frame, text=self.imagePath, \
font=("Times new roman", 12), bg="white", fg="red")
imagePathLabel.place(x=260-(len(self.imagePath)/2)*7, y=20)
# The function to Compress the chosen image
def Compress_Image(self):
if len(self.imagePath) == 0:
messagebox.showerror("Error", "Please Select an Image first")
else:
# Open the image
img = PIL.Image.open(self.imagePath)
# Getting the width and height of the image
width, height = img.size
# Resizing(reducing) the image(with the same height and width)
# using an Anti-aliasing technique
img = img.resize((width, height), PIL.Image.ANTIALIAS)
# Getting the filename and extension from the path of the image
filename, extension = \
os.path.splitext(os.path.basename(self.imagePath))
# Get the folder path from the user where the result file
# will be saved.
savetoPath = filedialog.askdirectory()
# The result filename(compressed image)
resultFilename = f"{savetoPath}/{filename}-compressed.jpg"
# Save the compressed image
try:
# Convert the image to RGB mode
img = img.convert("RGB")
# Saving the result image
img.save(resultFilename, \
quality=int(self.clicked.get()), optimize=True)
messagebox.showinfo("Done!","The Image has been compressed.")
# call the reset function
self.reset()
except Exception as es:
messagebox.showerror("Error", f"Error due to {es}")
# Function to reset some functionalities of the
# program to the previous state
def reset(self):
for widget in self.frame.winfo_children():
widget.destroy()
# Setting the image path to Null again
self.imagePath = ''
# The main function
if __name__ == "__main__":
# Creating an object of the Tk() class
root = Tk()
# Creating an object of the Compressor() class
obj = Compressor(root)
root.mainloop()
Output
Watch the entire video to know how does this Image Compressor actually work.
Summary
In this tutorial, we build an Image Compression Application using Python. Tkinter and Pillow, these two major python libraries help here to build this useful project. Users can compress (reduce the size of an image) any image without losing the quality of the actual one using this mini application.
It also offers users to select the quality of the resulting image to be saved later. The lower the number selected, the smaller the image size will be.
Do use this beautiful Python Image Compressor Tool to compress any of your images with different quality and save them later. Let me know how well it works for you in the comment section. You can comment back for any queries either. You will get a reply soon.
To get more lovely Tkinter Examples, visit the separate page created only for Python Projects. Some examples are given below.
👉Meditation App in Python Tkinter: Practice Deep Breathing
👉Language Translator App with Python Tkinter - Google Translate
👉Test Your Typing Speed with Python - Tkinter Project
👉An Advanced Alarm Clock using Python TkinterThanks for reading!
PySeek