How to compress images using Python and PIL?
Last Updated :
18 Aug, 2020
There are organizations who receive data form lakhs or more persons, which is mostly in form of text, with a few images. Most of you know that the text part is stored in databases in the form of tables, but what about the images? The images are small compared to the textual data but constitute a much higher space in terms of storage. Hence, to save on the part of space and keep running the processes smoothly, they ask the users to submit the compressed images. As most of the readers have a bit of CS background(either in school or college), they understand that using online free tools to compress images is not a good practice for them.
Till Windows 7, Microsoft used to give MS Office Picture Manager which could be used to compress images till an extent, but it also had some limitations.
Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork.
You'll get a screen like thisĀ
Assemble all the files in a folder and keep the file Compress.py in the same folder.
Run the python file with python.
Below is the Source Code of the file:
Python3
# run this in any directory
# add -v for verbose
# get Pillow (fork of PIL) from
# pip before running -->
# pip install Pillow
# import required libraries
import os
import sys
from PIL import Image
# define a function for
# compressing an image
def compressMe(file, verbose = False):
# Get the path of the file
filepath = os.path.join(os.getcwd(),
file)
# open the image
picture = Image.open(filepath)
# Save the picture with desired quality
# To change the quality of image,
# set the quality variable at
# your desired level, The more
# the value of quality variable
# and lesser the compression
picture.save("Compressed_"+file,
"JPEG",
optimize = True,
quality = 10)
return
# Define a main function
def main():
verbose = False
# checks for verbose flag
if (len(sys.argv)>1):
if (sys.argv[1].lower()=="-v"):
verbose = True
# finds current working dir
cwd = os.getcwd()
formats = ('.jpg', '.jpeg')
# looping through all the files
# in a current directory
for file in os.listdir(cwd):
# If the file format is JPG or JPEG
if os.path.splitext(file)[1].lower() in formats:
print('compressing', file)
compressMe(file, verbose)
print("Done")
# Driver code
if __name__ == "__main__":
main()
Folder Before Compression:
Folder before running fileCommand Line for executing Code:
PS: Please run code after getting into the directory.
Command Line for executing CodeFolder after execution of Code:
Folder after running code
You can clearly see the compressed file.
Similar Reads
Python | Copy and Paste Images onto other Image using Pillow In this article, we will learn how to copy an image over another image using pillow library. We will use image module from pillow and copy() and paste() methods to achieve this task. We will need to create copies of both images so that it does not affect the original image with the help of copy() me
2 min read
How To Get The Uncompressed And Compressed File Size Of A File In Python We are given a compressed file as well as uncompressed file. Our task is to get the size of uncompressed as well as compressed file in Python. In this article, we will see how we can get the uncompressed and compressed file size of a file in Python. What is Uncompressed And Compressed File?Uncompres
3 min read
How to Convert PIL Image into pygame surface image? In this article, we will know How to Convert PIL Image into pygame surface image. Pygame Surface Image: A surface that not only has fixed resolution and pixel format but also represents the image in Pygame is known as Pygame Surface Image. Are you constructing any game in Pygame in which you want t
4 min read
Image Enhancement in PIL The Python Imaging Library(PIL) adds powerful image processing capabilities. It provides immense file format support, an efficient representation, and fairly powerful image processing capabilities. The core image library is intended for fast access to data stored in very few basic pixel formats. It
4 min read
How to Concatenate image using Pillow in Python ? Prerequisites: Python Pillow Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, 'jpeg', 'png', 'gif', 'tiff', etc. In python, we can join two images using the Python image library also known as the pillow library. In
3 min read