Python Convert Images to Webp
- How to Convert Images to Webp in Python - Fedingo
- https://stackoverflow.com/a/47655463
- https://stackoverflow.com/a/57158589
```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<sub> = 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"} 三种后缀的文件。
参考资料
- Image Processing in Python: Algorithms, Tools, and Methods You Should Know - neptune.ai
- Essential Pil (Pillow) Image Tutorial (For Machine Learning People) - neptune.ai
相关:python