How to compress images with Python and PIL
This article shows you how to compress images with Python. First of all, we discuss the need for image compression. Nowadays, about 70% of online content is in the form of images. Therefore, it is crucial to pay attention to the number of times users have to wait to view the content on websites or applications. Moreover, on social media, people upload a considerable amount of images that need to be processed and optimized daily. Otherwise, their network will run out of memory storage. So, image compression is a vital task for every online platform.
Before reading the article, if you like to know more about Python, you could check out these two important articles:
The video
The importance of image compression
As mentioned in the previous paragraph, image compression is an essential task for every website. Let’s categorize the reasons into three major parts: SEO, storage, and bandwidth. When it comes to SEO, smaller images are needed, which means websites or apps will load faster, and viewers could use the content quickly because Google has stated that site speed is important in ranking. Optimized images are easier to store and reduce the operational cost of websites or apps. Moreover, with compressed images, websites or apps require less bandwidth, which means they could get more out of the hosting plan.
How to compress images with python
After learning the reasons for image compression, it’s time to go through hands-on practice and know how to compress images with Python. Python has many modules for image compression. Here are some of them:
- Pillow: This library builds on top of PIL and can be used for the following image formats: PNG, PPM, JPEG, GIF, BMP, and TIFF.
- Scikit-image – Scikit-learn is a machine learning package. The Scikit-image package allows for advanced images manipulation, allowing you to even return the images as NumPy arrays!
- Tinify – This package allows you to easily integrate with tinypng.com for receiving compressed images over an API.
- img4web – This script optimizes .jpg and .png images for the web. After running it, you’ll receive lossless compression for the images.
For this tutorial, we use the Pillow module for image compression.
Install the Pillow module
The first step of optimizing an image is to install the Pillow module. To install the updated Pillow framework on your Windows machine, run the following code in your command line or Powershell:
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow
To those unfamiliar with pip, pip is a Python package manager that helps Python developers install, uninstall, and manage Python modules. To install pip on Mac or Linux, click on the following links:
Open an image file in Python
We need to use two modules in this code. The first one is Pillow and the second one is Tkinter. Pillow is an image processing module, and the Tkinter is a GUI library of Python. We can open an image file, using the Tkinter module to ask the user to open an arbitrary image file. Look at the following code:
from PIL import Image
from tkinter.filedialog import *
file_path = askopenfilename()
img = Image.open(file_path)
myHeight, myWidth = img.size
print(myHeight, myWidth)
- Using line one, we import the “Image” from the PIL module.
- On line two, we import everything from “tkinter.filedialog”
- On line three, we ask the user to specify the path of their image file
- On line four, we give this path to the open method.
- On line five, we extract image size and store height and width.
- Line six is arbitrary. We use it to see the dimension of the image.
Image optimization in Python
To optimize the images volume, you need to utilize resize method which takes two parameter. The first one that is the dimension of the image is mandatory and the second one is an anti-aliasing filter. The following code optimizes your image, and it will be compressed.
img = img.resize((myHeight, myWidth), Image.ANTIALIAS)
Aliasing
In the filed of image processing, the aliasing phenomenon take place when there are a lot of high frequencies in the image and we want to downsample that. Look at the following image:

As you can see, some patterns called “Moire pattern” are in the left image, but the right image has not any of this pattern. Aliasing occurs when a signal is sampled at a less than twice the highest frequency present in the signal. To avoid the creation of signals at frequencies not present in the original signal, we need to filter out frequencies above half the sampling rate using a low pass filter. To read more you can click on this link.
Save the output
save_path = asksaveasfilename()
img.save(save_path + "_compressed.JPG")
To save the output image, we use “asksaveasfimename” to specify the path; then with save method, we save it with an arbitrary name.
Main code snippet
import PIL
from PIL import Image
from tkinter.filedialog import *
file_path = askopenfilename()
img = Image.open(file_path)
myHeight, myWidth = img.size
print(myHeight, myWidth)
img = img.resize((myHeight, myWidth), Image.ANTIALIAS)
save_path = asksaveasfilename()
img.save(save_path + "_compressed.JPG")
Output result

Conclusion
Awesome! You can try and tweak the parameters to fit your specific needs. I hope this script was handy for you to accelerate the development of your application. Thank you for reading!