How to Compress Images Using Python and PIL?


In today's digital era, images have become a necessary part of our lives. They play an important and significant role in communication and expression across a wide range of platforms, from social media to websites. However, high−quality images can consume a considerable amount of storage space and it'll result in slower website loading times and longer upload times. Image compression becomes applicable in this situation. By reducing the size of an image, you can ensure faster loading times, lower bandwidth usage, and more storage space.

In this article, we will look into the process of compressing images using Python and PIL. PIL, also known as the Python Imaging Library. It is a very useful and important library in Python that enables the opening, manipulation, and saving of various image file formats. By holding the capabilities of this library, we can easily compress our images and reap the benefits of faster loading times and reduced storage space.

Before we dive into the code, let's take a quick look at the different types of image compression.

Types of Image Compression

Mainly, there are two types of image compression: lossy and lossless.

Lossy Compression: Lossy compression is a type of compression where some data is lost during the compression process. This means that when you decompress the image, it will not be identical to the original image. However, the degree of difference is often not noticeable to the human eye. Examples of lossy compression include JPEG and GIF.

Lossless Compression: Lossless compression is a type of compression where no data is lost during the compression process. This means that when you decompress the image, it will be identical to the original image. Examples of lossless compression include PNG and TIFF.

Now that we have an understanding of the different types of image compression let's move on to the code.

How to Compress Images using Python and PIL

Step 1: Install PIL

The first step is to install the PIL library. For that, you can use pip. Open a terminal or command prompt and type the following command:

pip install Pillow

Success message

Collecting Pillow
  Downloading Pillow-8.4.0-cp39-cp39-win_amd64.whl (3.2 MB)
     |████████████████████████████████| 3.2 MB 2.1 MB/s
Installing collected packages: Pillow
Successfully installed Pillow-8.4.0

Step 2: Import the Required Libraries

After installing PIL, you need to import the required libraries into your Python program. For that, add the following lines of code at the beginning of your Python file:

from PIL import Image
import os

Step 3: Load the Image

Now after importing the required libraries let's load the image we want to compress. For that, we can use the Image.open() method from the PIL library.

image = Image.open('image.jpg')

This code opens the image named 'image.jpg' and assigns it to the variable 'image'.

Step 4: Resize the Image

After loading the image, we need to resize it to reduce its file size. For that, we can use the resize() method from the Image module.

width, height = image.size
new_size = (width//2, height//2)
resized_image = image.resize(new_size)

This code will resize the image to half of its original size. You can change the size of the image as per your requirements.

Step 5: Save the Compressed Image

After resizing the image, we need to save the compressed image. To do this, we can use the save() method from the Image module.

resized_image.save('compressed_image.jpg', optimize=True, quality=50)

After compressing the image, we need to save it as a new file. This code saves the compressed image as a file named 'compressed_image.jpg'. We can use the 'optimize' parameter to make sure that the image is optimized for web use. Additionally, we can adjust the quality of the image using the 'quality' parameter according to our needs.

Step 6: Verify the Compressed Image

At last, we need to verify whether the compressed image has been saved correctly or not. For that, we can compare the file sizes of the original image and the compressed image.

original_size = os.path.getsize('image.jpg')
compressed_size = os.path.getsize('compressed_image.jpg')

print("Original Size: ", original_size)
print("Compressed Size: ", compressed_size)

This code will print the file sizes of the original image and the compressed image. You can verify that the compressed image is smaller than the original image.

Here is the full implementation code

Example

from PIL import Image
import os

image = Image.open('image.jpg')

width, height = image.size
new_size = (width//2, height//2)
resized_image = image.resize(new_size)

resized_image.save('compressed_image.jpg', optimize=True, quality=50)

original_size = os.path.getsize('image.jpg')
compressed_size = os.path.getsize('compressed_image.jpg')

print("Original Size: ", original_size)
print("Compressed Size: ", compressed_size)

Output

Original Size:  1234567
Compressed Size:  543210

Note that the actual file sizes will depend on the input image used for the code. This is just an example.

Conclusion

To conclude, We discussed the difference between lossy and lossless compression and how the latter maintains the image quality better while consuming more space. We then walked through a step−by−step guide on how to compress an image using PIL in Python. We learned how to resize the image and save it in a compressed format, along with some best practices to ensure optimal results.

By following the steps outlined in this article, you can easily compress your images and optimize them for web use. You can adjust the quality and size of the compressed image to strike the right balance between image quality and file size. Whether you're a website developer or a hobbyist photographer, mastering image compression is a valuable skill that can enhance your digital presence.

Updated on: 20-Jul-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements