The Wayback Machine - https://web.archive.org/web/20240624214703/https://www.geeksforgeeks.org/how-to-compress-images-using-python-and-pil/
Open In App

How to compress images using Python and PIL?

Last Updated : 18 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 file

Folder before running file

Command Line for executing Code:

PS: Please run code after getting into the directory.

Command Line for executing Code

Command Line for executing Code

Folder after execution of Code:

Folder after running code

Folder after running code

You can clearly see the compressed file.



Similar Reads

Apply changes to all the images in given folder - Using Python PIL
Given a dataset of raw images, which usually need some pre-processing, which one person has to do physically. It is generally a task that requires some repetitive operation to perform for each image. Well, we can easily automate this process using some simple Python code and some libraries with it. So without further adieu, let's see how to apply c
2 min read
Finding Difference between Images using PIL
Python interpreter in itself doesn't contain the ability to process images and making out a conclusion to it. So, PIL(Python Imaging Library) adds image processing powers to the interpreter. PIL is an open-source library that provides python with external file support and efficiency to process images and their representations. Basically, PIL is des
2 min read
Loading Images in Tkinter using PIL
In this article, we will learn how to load images from user system to Tkinter window using PIL module. This program will open a dialogue box to select the required file from any directory and display it in the tkinter window.Install the requirements - Use this command to install Tkinter : pip install python-tkUse this command to install PIL : pip i
3 min read
Python | Numpy matrix.compress()
With the help of Numpy matrix.compress() method, we can select the elements from a matrix by passing a parameter as an array which contain the value 0 to not include the element or 1 to include the element in a matrix. Simply we pass the boolean array in matrix.compress() method. Syntax : matrix.compress() Return : Return a compressed array Example
1 min read
Numpy recarray.compress() function | Python
In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record arrays allow the fields to be accessed as members of th
3 min read
Python - Itertools.compress()
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Compress() The itertools.compress() falls under the
2 min read
zlib.compress(s) in python
With the help of zlib.compress(s) method, we can get compress the bytes of string by using zlib.compress(s) method. Syntax : zlib.compress(string) Return : Return compressed string. Example #1 : In this example we can see that by using zlib.compress(s) method, we are able to compress the string in the byte format by using this method. # import zlib
1 min read
gzip.compress(s) in Python
With the help of gzip.compress(s) method, we can get compress the bytes of string by using gzip.compress(s) method. Syntax : gzip.compress(string) Return : Return compressed string. Example #1 : In this example we can see that by using gzip.compress(s) method, we are able to compress the string in the byte format by using this method. # import gzip
1 min read
bz2.compress(s) in Python
With the help of bz2.compress(s) method, we can get compress the bytes of string by using bz2.compress(s) method. Syntax : bz2.compress(string) Return : Return compressed string. Example #1 : In this example we can see that by using bz2.compress(s) method, we are able to compress the string in the byte format by using this method. # import bz2 and
1 min read
numpy.compress() in Python
The numpy.compress() function returns selected slices of an array along mentioned axis, that satisfies an axis. Syntax: numpy.compress(condition, array, axis = None, out = None) Parameters : condition : [array_like]Condition on the basis of which user extract elements. Applying condition on input_array, if we print condition, it will return an arra
2 min read
Practice Tags :
three90RightbarBannerImg