Python batch converts images from png format to WebP format

高洛峰
Release: 2017-02-27 16:48:41
Original
2276 people have browsed it

Achieve the effect

Convert 1000 .png pictures located in the /img directory into .webp format and stored in the img_webp folder.

Python batch converts images from png format to WebP format
Source picture directory

Python batch converts images from png format to WebP format
Target picture directory

For batch generation of 1000 pictures, you can refer to this article:Use Python batch generates images of any size

Implementation example

##

import glob
import os
import threading

from PIL import Image


def create_image(infile, index):
  os.path.splitext(infile)
  im = Image.open(infile)
  im.save("img_webp/webp_" + str(index) + ".webp", "WEBP")


def start():
  index = 0
  for infile in glob.glob("img/*.png"):
    t = threading.Thread(target=create_image, args=(infile, index,))
    t.start()
    t.join()
    index += 1


if __name__ == "__main__":
  start()
Copy after login

Note: This project needs to reference the PIL library.

Considering that it is a large number of linearly intensive operations, multi-thread concurrency is used. When creating a thread object through

threading.Thread(), please note that the args parameter only accepts ancestors.

Here, we use the

Image.open() function to open the image.

Finally call the

save("img_webp/webp_" + str(index) + ".webp", "WEBP") method to write to the specified location in the specified format. The format parameter is the target format.

Okay, this article is basically over. Have you all learned it? I hope it will be of some help to everyone's study and work.

For more Python batch conversion of images from png format to WebP format, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template