Python converts images in batches from png to WebP,
Effect
Will be located in/img
1000 images in the directory.png
Image, convert.webp
Format.img_webp
Folder.
Source image directory
Target Image directory
For how to generate 1000 images in batches, refer to this article: generate images of any size in batches using Python.
Implementation example
import globimport osimport threadingfrom PIL import Imagedef 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 += 1if __name__ == "__main__": start()
Note:This project needs to be referencedPIL
Library.
Considering the large number of linear-intensive operations, multithreading concurrency is used. Passthreading.Thread()
Note the following when creating a thread object,args
The parameter only accepts the ancestor.
Here, we useImage.open()
Function to open the image.
Final callsave("img_webp/webp_" + str(index) + ".webp", "WEBP")
Method to write data to the specified location in the specified format. Whereformat
The parameter is in the target format.
Now, the content of this article is almost over. Have you learned it? I hope this will help you in your study and work.