Home > Article > Backend Development > How to compress images using Python and PIL?
In today’s digital age, images have become an essential part of our lives. They play an important and visible role in communication and expression on various platforms, from social media to websites. However, high-quality images can consume a lot of storage space and cause slower website loading times and longer upload times. Image compression becomes applicable in this case. By reducing the size of your images, you ensure faster loading times, lower bandwidth usage, and more storage space.
In this article, we will look at 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 can open, manipulate and save various image file formats. By mastering the capabilities of this library, we can easily compress images and reap the benefits of faster loading times and less storage space.
Before we dive into the code, let’s take a quick look at the different types of image compression.
There are two main types of image compression: lossy and lossless.
Lossy compression: Lossy compression is a type of compression that loses some data during the compression process. This means that when you decompress the image, it will not be exactly the same as the original image. However, this difference is usually imperceptible to the human eye. Examples of lossy compression include JPEG and GIF.
Lossless compression: Lossless compression is a type of compression that does not lose any data during the compression process. This means that when you decompress the image, it will be exactly the same as the original image. Examples of lossless compression include PNG and TIFF.
Now that we understand the different types of image compression, let's move on to code.
Step 1: Install PIL
The first step is to install the PIL library. For this 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. To do this, add the following line of code at the beginning of the Python file:
from PIL import Image import os
Step 3: Load the image
Now after importing the required libraries, let's load the images we want to compress. For this 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 this 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 needed.
Step 5: Save the compressed image
After resizing the image, we need to save the compressed image. In order 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 ensure that the image is optimized for the network. Additionally, we can use the 'quality' parameter to adjust the quality of the image as needed.
Step 6: Verify Compressed Image
Finally, we need to verify that the compressed image has been saved correctly. To do this, we can compare the file sizes of the original and compressed images.
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 out the file size of the original image and the compressed image. You can verify that the compressed image is smaller than the original image.
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)
Original Size: 1234567 Compressed Size: 543210
Please note that the actual file size will depend on the input image used for the code. This is just an example.
In summary, we discussed the difference between lossy and lossless compression, and how the latter is better at maintaining image quality, but takes up more space. We then walked through a step-by-step guide on how to compress images using PIL in Python. We learned how to resize and save images in a compressed format, as well as some best practices to ensure the best 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 compressed images to get the right balance between image quality and file size. Whether you're a website developer or an amateur photographer, mastering image compression is a valuable skill that can enhance your digital presence.
The above is the detailed content of How to compress images using Python and PIL?. For more information, please follow other related articles on the PHP Chinese website!