How to compress images using Python and PIL

How to Compress Images with Python and PIL

Some organizations receive data from dozens or more people, mostly in text form, with some images. Most of you know that the text portion is stored in a database in tables, but what about images? Compared to text data, images are small but take up a lot more space in terms of storage. Therefore, to save space and keep the program running smoothly, users are asked to submit compressed images. Since most readers have some computer science background (either in school or university), they understand that using free online tools to compress images is not a good idea.

Before Windows 7, Microsoft provided MS Office Picture Manager, which could be used to compress images to some extent, but it also had some limitations.

Those who know a little Python can install Python and use pip install Pillow in a command prompt (Linux users can use the terminal). Fork Pillow.

You should get a screen similar to this.

How to compress images using Python and PIL?

Gather all the files in a folder and place the file Compress.py in the same folder.

Run the Python file with Python.

Below is the source code for the file.

# 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
importsys
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

How to use Python and PIL to compress images?

Folder before running the file

Command line to execute the code

PS: Please run the code after entering the directory.

How to compress images using Python and PIL?

Command line for executing the code

Folder after executing the code.

How to compress images using Python and PIL?

Folder after running the code

You can clearly see the compressed file.

Leave a Reply

Your email address will not be published. Required fields are marked *