convert images to webp in python

How to Convert Images to Webp in Python

Webp is a highly optimized image format suitable for serving images on your websites & web applications. In some cases, webp image can be 9 times smaller than the same image in PNG format. So many webmasters and developers convert their images to webp format before serving them. There are many online tools to convert images to webp format. In this article, we will learn how to convert images to webp in python. It allows you to programmatically convert one or more images. You can also use this code in your website/application.


How to Convert Images to Webp in Python

We will use python language and pillow library for this purpose.


1. Prerequisites

Log into your virtual environment, if any, and create a folder webp in it.

$ mkdir webp
$ cd webp

Next, install pillow library using pip tool.

$ pip install Pillow

Create subfolder images in webp folder and add your PNG image files in it.

$ mkdir images


2. Create convert.py

Create a blank python file convert.py in webp folder.

$ sudo vi convert.py

Add the following line to it, to import Path from pathlib

from pathlib import Path

We will need this to read file paths of PNG files and also create their webp files, after conversion.

Next, add the following line to import pillow library.

from PIL import Image

The Pillow library we installed in previous step is referred to as PIL within python code. We will import Image module from this library.

Next, we will define convert_to_webp() function in our python file.

def convert_to_webp(source):
    """Convert image to WebP.

    Args:
        source (pathlib.Path): Path to source image

    Returns:
        pathlib.Path: path to new image
    """
    destination = source.with_suffix(".webp")

    image = Image.open(source)  # Open image
    image.save(destination, format="webp")  # Convert image to webp

    return destination

The above function basically accepts a file path as argument. It uses with_suffix() function to create path to webp file by replacing the suffix .png with .webp. We use Image.open() function to open PNG file, and call save() function, along with destination path to webp file. We also specify format option as webp to convert PNG to webp.

Save and close the file. Now you can easily call the function as shown.

convert_to_webp(Path("images/test.png"))

Here is the full code for your reference.

from pathlib import Path
from PIL import Image


def convert_to_webp(source):
    """Convert image to webp.

    Args:
        source (pathlib.Path): Path to source image

    Returns:
        pathlib.Path: path to new image
    """
    destination = source.with_suffix(".webp")

    image = Image.open(source)  # Open image
    image.save(destination, format="webp")  # Convert image to webp

    return destination


def main():
    paths = Path("images").glob("**/*.png")
    for path in paths:
        webp_path = convert_to_webp(path)
        print(webp_path)


main()

In the above code’s main function, we loop through the image files present in webp/images subfolder and call convert_to_path() function for each image file.

You can run the python file to convert all PNG images in images folder to webp formats.

$ python convert.py

In this article, we have learnt how to convert PNG to Webp images. You can use the same code to convert other image formats such as JPG, BMP, etc. to webp format. Just replace png with appropriate file extension in the above code. The Pillow library’s open function will automatically read images of many common formats and its save function will properly convert them to webp images.

Basically, all we do here is open the image using open() function, and save it as webp using save() function. It is equivalent to opening an PNG image in an image editor and then using Save As option to save it in your desired format. You can run it as a standalone python script or use it within your python application/website.

Also read:

How to Check if User Has Sudo Access
How to Combine JSON Files to CSV in Python
How to Convert JSON to CSV in Python
How to Find All Sudo Users in Linux
How to Check if Program Exists in Shell

Leave a Reply

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