Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
图片原地批量转换
#!/usr/bin/env python
#coding:utf-8
# Author: Sg4Dylan --<sg4dylan#gmail.com>
# Created: 9/28/2018
# ==========================================
# Any>WEBP Any>JPEG 图片原地批量转换
# ==========================================
# 使用方法: 把待转换的文件夹拖放到脚本上
import os
import sys
from PIL import Image
from tqdm import tqdm
import multiprocessing
target_root = ''
if len(sys.argv) > 1:
target_root = sys.argv[1]
to_webp = False
def convert_core(target_path):
im = Image.open(target_path)
im = im.convert('RGB')
if to_webp:
im.save(os.path.splitext(target_path)[0]+'.webp','WEBP')
else:
im.save(os.path.splitext(target_path)[0]+'.JPG', 'JPEG', quality=100, optimize=True)
os.remove(target_path)
def get_file_list():
file_path_list = []
for root, dirs, files in os.walk(target_root):
for name in files:
file_path_list.append(os.path.join(root, name))
return file_path_list
if __name__ == '__main__':
multiprocessing.freeze_support()
file_path_list = get_file_list()
with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as exec_pool:
with tqdm(total=len(file_path_list),ascii=True) as pbar:
for i, _ in tqdm(enumerate(exec_pool.imap_unordered(convert_core, file_path_list))):
pbar.update()
os.system('pause')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.