Python | フォルダ内の画像を一括でサムネイル化し、HTMLギャラリーを生成

Python
スポンサーリンク

短時間で「画像一覧ページ」を作りたいときの実用例です。pathlibでパス管理、Pillowでサムネイル生成、最後にHTMLを書き出します。Windows/macOS/Linux共通で動きます。


前提準備

  • ライブラリ: Pillow をインストール pip install pillow
  • フォルダ構成(例):
    • 入力: ~/Pictures/gallery_src
    • 出力: ~/Pictures/gallery_out(ここにサムネイルとHTMLを作成)

サンプルコード(サムネイル生成+HTMLギャラリー)

from pathlib import Path
from PIL import Image
import html

# 入出力ディレクトリ
src_dir = Path.home() / "Pictures" / "gallery_src"
out_dir = Path.home() / "Pictures" / "gallery_out"
thumb_dir = out_dir / "thumbs"

# 出力フォルダ作成
out_dir.mkdir(exist_ok=True)
thumb_dir.mkdir(exist_ok=True)

# 対象拡張子(必要に応じて追加)
extensions = {".jpg", ".jpeg", ".png", ".webp"}

# サムネイルサイズ(長辺をこのサイズ以内に)
thumb_size = (240, 240)

items = []
for img_path in sorted(src_dir.iterdir()):
    if img_path.suffix.lower() not in extensions or not img_path.is_file():
        continue

    # サムネイルパスを決定
    thumb_path = thumb_dir / (img_path.stem + "_thumb.jpg")

    # 画像を開いてサムネイル作成
    with Image.open(img_path) as img:
        # サムネイル化(アスペクト比維持)
        img.thumbnail(thumb_size)
        # JPEGで軽量保存(RGBへ変換しておく)
        if img.mode != "RGB":
            img = img.convert("RGB")
        img.save(thumb_path, "JPEG", quality=85)

    # ギャラリー用に情報を保持(HTML用にエスケープ)
    items.append({
        "full": img_path.name,                 # 元画像ファイル名(同一フォルダにコピーしない場合は注意)
        "thumb": f"thumbs/{thumb_path.name}",
        "title": html.escape(img_path.stem),
    })

# 元画像を出力フォルダへコピーしたい場合はコメント解除
# import shutil
# for item in items:
#     shutil.copy(src_dir / item["full"], out_dir / item["full"])

# シンプルなHTMLテンプレートを生成
html_path = out_dir / "index.html"
html_content = f"""<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>画像ギャラリー</title>
<style>
  body {{ margin: 0; font-family: system-ui, sans-serif; background:#111; color:#eee; }}
  header {{ padding: 16px; text-align:center; font-size: 18px; }}
  .grid {{
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
    padding: 12px;
  }}
  .card {{
    background: #1b1b1b; border-radius: 8px; overflow: hidden; border:1px solid #2a2a2a;
  }}
  .thumb {{
    display:block; width:100%; height:auto; aspect-ratio: 1 / 1; object-fit: cover;
    background:#222;
  }}
  .meta {{ padding: 8px; font-size: 12px; color:#bbb; }}
  a {{ color: inherit; text-decoration: none; }}
  a:focus-visible {{ outline: 2px solid #4ea3ff; outline-offset: 2px; }}
</style>
</head>
<body>
<header>フォルダ内の画像ギャラリー({len(items)}枚)</header>
<main class="grid">
{"".join(f'''
  <div class="card">
    <a href="{html.escape(item["full"])}" target="_blank" rel="noopener">
      <img class="thumb" src="{html.escape(item["thumb"])}" alt="{item["title"]}">
      <div class="meta">{item["title"]}</div>
    </a>
  </div>
''' for item in items)}
</main>
</body>
</html>
"""

html_path.write_text(html_content, encoding="utf-8")
print(f"HTMLギャラリーを作成しました: {html_path}")
print(f"サムネイル保存先: {thumb_dir}")
Python

使い方のポイント

  • 対象拡張子: 必要なら extensions".gif", ".tiff" などを追加。
  • サムネイルの軽量化: quality=85 を下げるほどファイルサイズが小さくなる。Web用途なら 75–85 が目安。
  • 元画像の参照方法: 上のコードは「元画像は src_dir にある」と仮定。HTMLから開けるようにするには、元画像も out_dir にコピーするか、href../ 相対パスに調整。
  • 表示調整: CSSの grid-template-columnsgap を好みに合わせて変更可能。

よくある拡張・改善

  • Lazy Load: <img loading="lazy" ...> を付けて初期表示を高速化。
  • メタ情報: 撮影日時などEXIFを読み取り、meta に表示。
  • 並び順: sorted()key 引数でファイル更新日時や名前順などに変更。
  • 安全性: HTMLに埋め込むテキストは html.escape() でエスケープ済み。ファイル名に特殊文字がある場合も安心。

まとめ

  • pathlib: OSを気にせずパス操作が簡単。
  • Pillow: アスペクト比維持でサムネイル化、JPEGで軽量保存。
  • HTML自動生成: シンプルなテンプレートで即ギャラリー化。

Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました