Pillow: optimize images with Python

Optimizing images is key to making websites faster and improving SEO. With the advent of WebP format, it is possible to provide quality images but much "lighter". In this article we discover how to transform jpg and/or png images into the webp format using a few lines of code written in Python and the Pillow library.

Share

Reading time: 4 minutes

Nowadays, the loading speed of a website on mobile devices has become an important ranking factor on Google adopting the mobile-first approach for SEO. Since mobile devices do not have the same processing power as computers, it becomes very important to optimize all “bandwidth heavy” elements such as images to increase page loading speed. A faster loading speed on mobile devices implies a better ranking of the website in Google searches. Obviously, this is not the only factor that affects SEO, but it is something to consider when designing and developing a website.

Studies show that a site that is very slow in loading pages implies less user engagement. This means that the average user will be demotivated to browse the site and, in the case of e-commerce, buy the products and/or services offered. Images are usually one of the main sources of slow page loading.

Thanks to advances in image compression, today it is possible to use different formats that reduce the “heaviness” of the file while maintaining a high quality. Among these, the most popular format in recent years is WebP.

WebP is a modern image format that provides superior lossless and lossy compression for images on the web. Using WebP, you can create smaller and richer images that make the site that encompasses them faster.

On average, lossless images in WebP format are about 26% smaller in size than PNG format. In contrast, lossy WebP images are, on average, 25-34% smaller than comparable JPEG images with an equivalent SSIM quality index.

WebP lossless supports transparency (also known as alpha channel) at a cost of only 22% more bytes. For cases where RGB lossy compression is acceptable, WebP lossy also supports transparency, typically providing 3× smaller file sizes than PNG.

In this article we’ll see how to convert PNG or JPG images to the WEBP format using Python’s Pillow library.

Compression via Pillow

Before proceeding with image resizing, you need to install the Pillow library in your development environment. The fastest method is to use the following command:

pip install pillow 

Once the library is installed you can include it in your code using the following line of code

import PIL 

In the following code is an example of a function that allows you to compress all the images contained in a directory and save them in WEBP format in a specific path. You can use this example as a starting point to include in your applications and/or websites that need image optimization.

The variables to change are definitely path, export_path, while you can use the same code structure to convert your images to different formats.

import PIL
from PIL import Image
import os 

path= '/source/'
export_path = '/dest/'

images = os.listdir(path)

def resize():
    for image in images:
        image_name = image.split('.', 1)[0]
        fixed_height = 250
        image = Image.open(path+image)
        height_percent = (fixed_height / float(image.size[1]))
        width_size = int( float(image.size[0]) * float(height_percent) )
        image = image.resize((width_size, fixed_height), PIL.Image.NEAREST)
        image.save(export_path+image_name+ '.webp', 'webp', optimize=True, quality=90)

resize() 

In this example, compression implies resizing the final image to a fixed height of 250 pixels while keeping the aspect ratio unchanged.  You can change the height at will. If you need the output images to have a fixed height and width, you can substitute the following line in the code.

image = image.resize((width_size , fixed_height), PIL.Image.NEAREST) 

with the following code:

width = 205
height = 250
image = image.resize((width , height)) 

Or if you want to keep the original size of the images unchanged, simply remove the resize command.

To give you an idea of the potential of compression I experimented with a folder containing images in JPG and PNG format. The original size was 906 MB.

Applying a compression with a fixed height resize of 250 pixels and a quality of 90% the output size of the folder was 174 MB, i.e. a reduction of about 80%.

On the other hand, applying a fixed size for both height and width resulted in a reduction of almost 86%. Conversely, maintaining the original size of each image resulted in a reduction of only 3%. You can see, then, how image size and quality affect the compression factor.

Studies

A study presented by Google compared the compression of WebP and JPEG images based on the new encoder released in libwebp. The study observed that the average WebP file size is 25%-34% smaller than the JPEG file size at an equivalent SSIM index. The SSIM vs bpp graphs showed that WebP consistently requires fewer bits per pixel than JPEG for the same SSIM index. These observations indicate that WebP can provide significant compression improvements over JPEG.

Another study conducted many years earlier had already highlighted the potential of the webp format. The study obtained reductions ranging from about 10% to as much as 40%. The results, as shown in the figure below, showed that WebP achieved better compression than other formats, especially for smaller images.

Recommended Readings

More To Explore

Artificial intelligence

AI: the best prompt techniques for leveraging LLMs

Prompt techniques are the basis for the use of LLMs. There are several studies and guidelines for obtaining the best results from these models. Let us analyze some of them to extract the basic principles that will allow us to obtain the desired answers according to our task.

Artificial intelligence

AI: create a chatbot with your own data

ChatGPT allows us to have a virtual assistant at our complete disposal. However, it has one major limitation: it does not know our private data. How can we build our own virtual assistant, or rather a chabot, that uses our data and does not require us to invest money? Let’s find out how to build one using open LLM, free computational environments such as Colab, and Python libraries to manage PDF files and create simple and intuitive web interfaces.

Leave a Reply

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

Design with MongoDB

Design with MongoDB!!!

Buy the new book that will help you to use MongoDB correctly for your applications. Available now on Amazon!