Home > Article > Backend Development > Python batch converts images from png format to WebP format
Achieve the effect
Convert 1000 .png
pictures located in the /img
directory into .webp
format and stored in the img_webp
folder.
Source picture directory
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()
Note: This project needs to reference the PIL library.
threading.Thread(), please note that the
args parameter only accepts ancestors.
Image.open() function to open the image.
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.