Tianhe Gao

python-convert-images-to-webp

```bash mkdir pytowebp && cd $_ python -m venv venv –upgrade-deps . venv/env/activate (venv) pip install Pillow (venv) emacs main.py ```

main.py:

```py from pathlib import Path from PIL import Image

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

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

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

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

return destination

def main(): allfilespath = Path(".").glob(r"*/") for singlefile in allfilespath: if singlefile.suffix in {".png", ".jpg", ".jpeg"}: # PurePath.suffix 查询文件扩展名 webppath = converttowebp(singlefile) print(webppath)

main() ```

最难的部分是同时找到包含 `{".png", ".jpg", ".jpeg"}` 三种后缀的文件。


参考资料

  1. [Image Processing in Python: Algorithms, Tools, and Methods You Should Know - neptune.ai](https://neptune.ai/blog/image-processing-python)
  2. [Essential Pil (Pillow) Image Tutorial (For Machine Learning People) - neptune.ai](https://neptune.ai/blog/pil-image-tutorial-for-machine-learning)

No notes link to this note