Automation Lab
•
2024-02-01
大量画像を一括リサイズ:Webサイト運営を劇的に効率化するツール
所要時間
10 MIN
必要環境
Python 3.x, Pillow
Webサイトの運営やSNS投稿で、大量の画像サイズを整える作業は苦行です。今回は、フォルダ内の全画像を自動で読み込み、アスペクト比を維持したまま指定の横幅にリサイズするスクリプトを作成します。
1. 必要なライブラリ:Pillow
Pythonで画像を扱うなら「Pillow」一択です。以下のコマンドでインストールしましょう。
pip install Pillow
2. 自動化スクリプトの全コード
このコードは input フォルダ内の画像を読み込み、横幅800pxに統一して output フォルダに保存します。
from PIL import Image
import os
# 入力フォルダ、出力フォルダ、変更後の横幅を指定
input_dir = 'input'
output_dir = 'output'
target_width = 800
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in os.listdir(input_dir):
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
# 画像を開く
img = Image.open(os.path.join(input_dir, file))
# 比率を計算して高さを決定
ratio = (target_width / float(img.size[0]))
target_height = int((float(img.size[1]) * float(ratio)))
# リサイズ(高品質なLANCZOSフィルターを使用)
img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)
# 保存
img.save(os.path.join(output_dir, file), optimize=True, quality=85)
print(f"完了: {file}")
3. 実用的なカスタマイズ案
- ロゴ(透かし)の自動挿入: 全ての画像の右下に自分のロゴを自動で入れるように改造可能です。
- WebP形式への変換:
img.save(..., format='WEBP')とするだけで、Webサイトに最適な軽量形式に変換できます。
注意点: 元の画像を上書きしないよう、必ず別の出力フォルダ(outputなど)に保存するようにしましょう。