屬性
- 目標: 將一資料夾內圖片全數轉換成 webp 格式。
- 實現語言: python
- 細節功能: 多線程、進度條、指定資料夾
代碼全文
'''
腳本功能: 以資料夾為單位,轉換資料夾裡的圖片成 webp
'''
from PIL import Image
import os, sys, logging, argparse
import multiprocessing
from pathlib import Path
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor
parser = argparse.ArgumentParser(description='Convert images in a folder to webp format.')
parser.add_argument('-p', '--path', help='Path to the folder containing images')
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logging.basicConfig(format='[%(asctime)s] %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
def convert(file, quality):
with Image.open(file) as img:
new_file = Path(file).with_suffix('.webp')
try:
img.save(new_file, 'webp', quality=80)
except Exception as e:
logging.error(f"Error converting {file}: {str(e)}")
else:
# 刪除原圖
try:
Path(file).unlink()
except:
logging.error(f"Unknow reason cause original image {file} cannot be deleted.")
if __name__ == '__main__':
args = parser.parse_args()
path = args.path
num_cores = multiprocessing.cpu_count()
num_workers = num_cores - 1
show_path = Path(path).parts[-1] # 取得資料夾名稱 (原本的 path 為完整路徑)
for root, dirs, files in os.walk(path):
ext = [".jpg", ".jpeg", ".png"]
img_files = [os.path.join(root, file) for file in files if file.lower().endswith(tuple(ext))]
# 若無任何符合格式的圖片
if len(img_files)==0:
logging.warning(f"There is no any images in {show_path}. Process will exit.")
sys.exit(1)
description = f"[{show_path}] {len(img_files)} images converting..."
with ThreadPoolExecutor(max_workers=num_workers) as executor:
list(tqdm(executor.map(convert, img_files), total=len(img_files), desc=description))
评论区