""" Tiles preview renders into one sheet with captions. python build/contact_sheet.py [ ...] The caption is the file name without its prefix (text before the first underscore) and extension. """ import os import sys from PIL import Image, ImageDraw, ImageFont out, cols, scale = sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) files = sys.argv[4:] ims = [Image.open(f).convert("RGB") for f in files] w, h = ims[0].size w, h = int(w * scale), int(h * scale) rows = (len(ims) + cols - 1) // cols sheet = Image.new("RGB", (w * cols, h * rows), (20, 20, 20)) try: font = ImageFont.truetype("arialbd.ttf", max(12, h // 26)) except Exception: # noqa: BLE001 font = ImageFont.load_default() d = ImageDraw.Draw(sheet, "RGBA") for i, (im, f) in enumerate(zip(ims, files)): x, y = (i % cols) * w, (i // cols) * h sheet.paste(im.resize((w, h), Image.LANCZOS), (x, y)) cap = os.path.splitext(os.path.basename(f))[0] cap = cap.split("_", 1)[1] if "_" in cap else cap tw = d.textlength(cap, font=font) d.rectangle([x + 6, y + 6, x + tw + 18, y + 12 + font.size + 6], fill=(0, 0, 0, 170)) d.text((x + 12, y + 9), cap, fill=(255, 255, 255, 255), font=font) sheet.save(out) print("wrote", out, sheet.size)