Compress PNG image in Python using PIL

Compress PNG Image In Python Using PIL

Compressing images to speed up image processing and analysis is very common nowadays. Its popularity can be attributed to reducing the irrelevancy and redundancy of the image data. To transmit data in an efficient form and to reduce the number of bits required to render an image.

Storage optimization can be achieved by compressing image files. Efficient file transfer with lower network bandwidth is also the reason why compressing images is the need of the hour.

The pace at which technological advances are happening around the world today, we need to enhance the speed at which we upload images for official purposes where the resolution doesn’t matter as much as the proof of the document.

Using the library Pillow in Python, we can compress images in any format such as JPG, PNG, etc.

To compress images in Python, use the Pillow library. Install it with pip install pillow, then create a function to resize and save the image with optimized quality. Call this function with your image file to get a compressed version, allowing for storage optimization and faster transfers while maintaining image quality.

Using Pillow for Image Compression in Python

In Python, numerous libraries contain pre-defined functions for a variety of purposes. Pillow (PIL) is a popular library in Python for image compression. Using Pillow, we can compress and reduce the size of images easily.

On websites that require tons of image uploads from lakhs and lakhs of users, image compression becomes a need more than just a want.

Pillow is a free and open-source python library used for image processing, manipulating and saving and opening files in various formats like PNG, JPG, etc. It is one of the more efficient methods which can be used for faster access to the pixel data of an image. It was developed by Jeffrey A Clark and is supported by Tidelift. To know more about Pillow, click here.

Advantages and Disadvantages of Image Compression

There are many advantages and disadvantages of image compression in python. Some of them are:

Advantages:

  • Makes an image more easily portable.
  • To increase the speed of file transfer, such as, uploading or downloading of images to and from the internet.
  • Reduced image sizes consumes less bandwidth.
  • Lossless image reduction will retain almost the same quality and look of the image while removing the irrelevant pixel data in order to speed up image processing.
  • In websites that require large amounts of image data from millions of users, compression helps in optimizing speed and memory usage.
  • Compressed images can be easily shared through emails and social media sites faster.

Disadvantages:

  • Results in decreased image quality.
  • may lead to loss of important pixel data.
  • May not sometimes support layering of images.

Suggested: Python Pillow Module – A Brief Introduction.

Compressing Images with Python and PIL (Code)

In this section of the tutorial, we will get into the code for implementing the pillow library to compress an image in python.

We will start by importing the required modules which should be installed in your system before proceeding further. If you don’t already have them, run the following in your command prompt.

pip install pillow

The image that I will be using is given below. You can download it, or you can use whatever image you want in .PNG format.

Sample Image
Sample Image

If you click on the properties of your image, you can see the size of the image before compression. The original size of my image is 0.99MB(1017.24Kilobytes), that is given below,

Original Image Properties
Original Sample-Image Properties

Now, let’s look at the code to reduce it’s size:

# importing the required modules
import os
from PIL import Image

# Function to compress the image
def compressimages(image_file):
    # accessing the image file
    filepath = os.path.join(os.getcwd(), image_file)
    # maximum pixel size
    maxwidth = 1200
    # opening the file
    image = Image.open(filepath)
    # Calculating the width and height of the original photo
    width, height = image.size
    # calculating the aspect ratio of the image
    aspectratio = width / height

    # Calculating the new height of the compressed image
    newheight = maxwidth / aspectratio

    # Resizing the original image
    image = image.resize((maxwidth, round(newheight)))

    # Saving the image
    filename = "Compressed.PNG"
    image.save(filename, optimize=True, quality=85)
    return


# driver code
image_file = "path_of_samplephoto.png"
# calling the function
compressimages(image_file)
print(
    "The given image has been compressed, download the files to notice the difference in file size."
)

The output would include a newly created image called “Compressed.PNG” in the directory where your original image is stored. But this new image will be smaller in size. Let’s look at the dimensions of the new image.

Compressed Image Properties
Compressed Image Properties

The size of the image, that is the resolution has now decreased to 986KB from 0.99MB, hence the compression has been successful. The compressed image should be fine because it is supposed to be of “lossless” in terms of image quality. Let’s look at the compressed image.

Compressed 1
Compressed Image.

The image, though smaller in size retains almost its original quality and doesn’t appear smudgy! That’s how you compress an image in python using PIL.

Conclusion

In this article, we have learned how to compress images in Python using one of the image processing, open-source libraries called Pillow.

PIL or pillow is one of the most powerful image manipulating modules in Python. It is most commonly used for reducing image size, implicitly or explicitly converting image from one format to another, save images, compressing images and much more.

As technology continues to advance, efficient image compression becomes increasingly important for both beginners and experts. How will image compression techniques evolve to meet the demands of future applications?