environment
- python 3.8
- pillow 9.4.0
Introduction
WebP
is an image format developed by Google
in 2010. It is mainly used in the network environment and provides lossless and lossy compression. Website developers can use WebP
to create images with smaller size and richer details, so as to speed up the opening speed of the website and improve the user experience of visitors. In the future, the pictures on this site will also use WebP
format, which can greatly save the disk space of the server .
Practical
Here we use the pillow
library to convert the image format, first install it through pip
pip install -U pillow
The principle of implementation is actually very simple. Use pillow
to open the original file, usually png
and jpg
, and then save it in webp
format. See the sample code below
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) image.save(destination, format="webp") return destination if __name__ == '__main__': paths = Path("C:\\Users\\\Administrator\\Desktop\\images").glob("**/*.png") for path in paths: webp_path = convert_to_webp(path) print(webp_path)
It can be seen that the file size gap between the original png
image and the processed webp
is still quite large
This article is transferred from https://xugaoxiang.com/2023/02/14/convert-image-to-webp/
This site is only for collection, and the copyright belongs to the original author.