File size: 4,618 Bytes
fde9a21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | #!/usr/bin/env python3
"""Create paginated, label-rich contact sheets without cropping source images."""
from __future__ import annotations
import argparse
import math
import re
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff"}
def natural_key(path: Path) -> list[object]:
# Include recursive parent paths: generic leaf names such as ``A.png`` and
# ``B.png`` must stay grouped by their naturally sorted case directory.
return [
int(part) if part.isdigit() else part.lower()
for part in re.split(r"(\d+)", path.as_posix())
]
def font(size: int) -> ImageFont.ImageFont:
for path in (
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
):
if Path(path).exists():
return ImageFont.truetype(path, size=size)
return ImageFont.load_default()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input_dir", type=Path)
parser.add_argument("output", type=Path, help="Base output path; _01, _02, ... are appended.")
parser.add_argument("--columns", type=int, default=3)
parser.add_argument("--per-page", type=int, default=12)
parser.add_argument("--cell-width", type=int, default=720)
parser.add_argument("--cell-height", type=int, default=520)
parser.add_argument("--recursive", action="store_true")
return parser.parse_args()
def collect_images(root: Path, recursive: bool) -> list[Path]:
iterator = root.rglob("*") if recursive else root.glob("*")
return sorted(
[path for path in iterator if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES],
key=natural_key,
)
def output_for_page(base: Path, page: int, total_pages: int) -> Path:
if total_pages == 1:
return base
return base.with_name(f"{base.stem}_{page + 1:02d}{base.suffix}")
def main() -> None:
args = parse_args()
paths = collect_images(args.input_dir, args.recursive)
if not paths:
raise ValueError(f"No images found in {args.input_dir}")
if args.columns < 1 or args.per_page < 1:
raise ValueError("--columns and --per-page must be positive")
total_pages = math.ceil(len(paths) / args.per_page)
title_font = font(25)
meta_font = font(18)
label_height = 76
image_height = args.cell_height - label_height
for page in range(total_pages):
subset = paths[page * args.per_page : (page + 1) * args.per_page]
rows = math.ceil(len(subset) / args.columns)
sheet = Image.new(
"RGB",
(args.columns * args.cell_width, rows * args.cell_height),
(224, 224, 224),
)
draw = ImageDraw.Draw(sheet)
for local_index, path in enumerate(subset):
global_index = page * args.per_page + local_index + 1
column = local_index % args.columns
row = local_index // args.columns
x0 = column * args.cell_width
y0 = row * args.cell_height
with Image.open(path) as source:
image = ImageOps.exif_transpose(source).convert("RGB")
dimensions = image.size
image.thumbnail((args.cell_width - 16, image_height - 16), Image.Resampling.LANCZOS)
paste_x = x0 + (args.cell_width - image.width) // 2
paste_y = y0 + (image_height - image.height) // 2
sheet.paste(image, (paste_x, paste_y))
draw.rectangle((x0, y0, x0 + args.cell_width - 1, y0 + args.cell_height - 1), outline=(80, 80, 80), width=2)
label_y = y0 + image_height
draw.rectangle((x0, label_y, x0 + args.cell_width, y0 + args.cell_height), fill=(255, 255, 255))
display_name = path.name
if len(display_name) > 54:
display_name = display_name[:51] + "..."
draw.text((x0 + 12, label_y + 7), f"{global_index:02d} {display_name}", font=title_font, fill=(0, 0, 0))
draw.text(
(x0 + 12, label_y + 41),
f"{dimensions[0]} x {dimensions[1]} | {path.stat().st_size / (1024 * 1024):.2f} MiB",
font=meta_font,
fill=(45, 45, 45),
)
output = output_for_page(args.output, page, total_pages)
output.parent.mkdir(parents=True, exist_ok=True)
sheet.save(output, quality=93, subsampling=0)
print(output)
if __name__ == "__main__":
main()
|