3

图片转换成 WebP 格式

 1 year ago
source link: https://xugaoxiang.com/2023/02/14/convert-image-to-webp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

WebPGoogle 公司在2010年开发的一种图片格式,主要用于网络环境,提供了无损和有损压缩。网站开发者们可以使用 WebP 来创建尺寸更小、细节更丰富的图片,以此来加快网站打开的速度,提升访问者的用户体验。今后,本站中的图片也将采用 WebP 格式,可以大大节省服务器的磁盘空间。

这里使用 pillow 这个库来实现图片格式的转换,首先通过 pip 来安装

pip install -U pillow

实现的原理其实非常简单,利用 pillow 打开原文件,通常是 pngjpg,然后使用 webp 格式保存就可以了,看下面的示例代码

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)

可以看到,原始的 png 图片和处理后的 webp,文件大小差距还是蛮大的

e4df8e5db3b9d332.webp

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK