白背景に
#FFFFFF の#AAAAAA をそのままタイトルsave() する
WCAG のコントラスト比を計算する
WCAG 2.1 Success Criterion 1.4.3 は
まず sRGB の
def relative_luminance(r8: int, g8: int, b8: int) -> float:
def linearize(c8: int) -> float:
c = c8 / 255
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
return 0.2126 * linearize(r8) + 0.7152 * linearize(g8) + 0.0722 * linearize(b8)
次に 2 色の
def contrast_ratio(fg: tuple[int, int, int], bg: tuple[int, int, int]) -> float:
l1 = relative_luminance(*fg[:3])
l2 = relative_luminance(*bg[:3])
lighter, darker = (l1, l2) if l1 >= l2 else (l2, l1)
return (lighter + 0.05) / (darker + 0.05)
WCAG AA の
Pillow で save() の前にゲートをかける
from PIL import Image, ImageDraw, ImageFont
WCAG_AA_THRESHOLD = 4.5
def generate_og_image(title: str, output_path: str) -> None:
BG_COLOR = (255, 255, 255)
TEXT_COLOR = (30, 30, 30)
ratio = contrast_ratio(TEXT_COLOR, BG_COLOR)
if ratio < WCAG_AA_THRESHOLD:
raise ValueError(f"コントラスト比 {ratio:.2f}:1 < {WCAG_AA_THRESHOLD}:1")
img = Image.new("RGB", (1200, 630), BG_COLOR)
draw = ImageDraw.Draw(img)
draw.text((80, 200), title, fill=TEXT_COLOR, font=_load_font(size=64))
img.save(output_path, "PNG")
img.save() のraise する
フォント: macOS はヒラギノ 0 円、Linux は Noto CJK
import os, sys
def _load_font(size: int) -> ImageFont.FreeTypeFont:
if sys.platform == "darwin":
# macOS: ヒラギノ角ゴシック W3 はシステム同梱。追加コスト 0 円
candidates = [
"/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc",
"/Library/Fonts/ヒラギノ角ゴシック W3.ttc",
]
else:
# Ubuntu/GitHub Actions: sudo apt-get install -y fonts-noto-cjk
# Vercel/Lambda: repo に bundle して __file__ 相対パスで参照
candidates = [
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
os.path.join(os.path.dirname(__file__), "fonts", "NotoSansJP-Regular.ttf"),
]
for path in candidates:
if os.path.exists(path):
return ImageFont.truetype(path, size=size)
raise FileNotFoundError(f"日本語フォントが見つかりません: {candidates}")
macOS ではsudo apt-get install -y fonts- で
ここで 30 分溶かした。FileNotFoundError がos.path.exists() で
やらかした具体例
最初にBG_COLOR=#E8F4FD、TEXT_COLOR=#7BB3CC という設定が
気づいたのは Twitter(X) Analytics で
まとめ
- WCAG の
相対輝度式を Python に 落とすだけで contrast_ratio()が作れる img.save()の前に チェックして raise。後回しは 量産事故を 招く - macOS では
ヒラギノが 0 円で 使える。 Linux は fonts-noto-cjk、サーバーレスは フォント bundle - 足切りは AA 通常
テキストの 4.5:1 にしておくと、 リサイズ・ 圧縮後の 余裕が 生まれる
次回は
SparMate — 格闘技の
NetaPair —
BoardLink — ボドゲ・
Cosoado Lab