萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 批量按比例縮放圖片:Pillow 實現目錄級縮圖腳本

需求背景

百張原圖需按比例縮小(如 12%),用 Photoshop 逐張處理太慢。Python + Pillow 幾行代碼即可完成目錄級批量處理,自動建立輸出目錄、保持比例、保存為 JPEG。

完整腳本


# -*- coding: cp936 -*-
from PIL import Image
import glob, os

def batch_resize():
    src_pattern = r'D:\1\*.JPG'
    dst_dir = r'D:\22'
    scale = 0.12  # 縮放比例 12%

    # 確保輸出目錄存在
    if not os.path.isdir(dst_dir):
        os.makedirs(dst_dir)

    for filepath in glob.glob(src_pattern):
        filename = os.path.basename(filepath)
        name, _ = os.path.splitext(filename)

        with Image.open(filepath) as im:
            w, h = im.size
            new_size = (int(w * scale), int(h * scale))
            im_resized = im.resize(new_size, Image.LANCZOS)  # 高質量重採樣
            out_path = os.path.join(dst_dir, name + '.jpg')
            im_resized.save(out_path, 'JPEG', quality=85)

    print('批量縮圖完成!')

if __name__ == '__main__':
    batch_resize()

關鍵點解析

  • Image.LANCZOS:高質量下採樣濾波器(舊版為 Image.ANTIALIAS),避免鋸齒與摩爾紋。
  • with Image.open(...) as im:上下文管理器自動關閉檔案句柄,防止大量檔案導致「Too many open files」。
  • os.makedirs(dst_dir, exist_ok=True):Python 3.2+ 可單行建立多層目錄。
  • quality=85:JPEG 品質/體積平衡點,可按需調整 75~95。

進階擴充:保留目錄結構、多格式、並行處理


from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

def resize_one(src_path, dst_root, scale, quality):
    rel = src_path.relative_to(SRC_ROOT)
    dst_path = dst_root / rel.with_suffix('.jpg')
    dst_path.parent.mkdir(parents=True, exist_ok=True)
    with Image.open(src_path) as im:
        im.resize((int(im.width*scale), int(im.height*scale)), Image.LANCZOS)\
          .save(dst_path, 'JPEG', quality=quality)

SRC_ROOT = Path(r'D:\photos')
DST_ROOT = Path(r'D:\thumbs')
SCALE = 0.2
QUALITY = 80

with ThreadPoolExecutor(max_workers=8) as pool:
    for f in SRC_ROOT.rglob('*.[jJ][pP][gG]'):
        pool.submit(resize_one, f, DST_ROOT, SCALE, QUALITY)

總結

Pillow + glob/pathlib + 線程池,幾十行代碼構建出生產級批量縮圖管線,輕鬆應對萬張圖片處理需求。

copyright © 萬盛學電腦網 all rights reserved