Gallery thumbnails
Goal. Produce 320, 640 and 1280-pixel-wide WebP versions of every photo for a responsive gallery. Inputs: scene.png. Needs: Hokusai 2.2.2.
// One source, several sizes, produced concurrently: pipelines are immutable, so they branch safely.let source = try Hokusai(url: URL(fileURLWithPath: "scene.png")).autoOrient()let widths = [320, 640, 1280]
try await withThrowingTaskGroup(of: (Int, OutputInfo).self) { group in for width in widths { group.addTask { // withoutEnlargement: never upscale a small original. let info = try await source .resize(width: width, withoutEnlargement: true) .webp(quality: 80) .write(to: URL(fileURLWithPath: "thumb-\(width).webp")) return (width, info) } } for try await (width, info) in group { print("\(width) →", info.width, "×", info.height, info.byteCount, "bytes") }}
320 · 4.1 KBWEBP · 320 × 200 · 4 KB 
640 · 9.3 KBWEBP · 640 × 400 · 9 KB 
1280 · 20.3 KBWEBP · 1280 × 800 · 20 KB
How it works
Section titled “How it works”- A pipeline is immutable, so one
sourcecan branch into three outputs; the task group evaluates them concurrently (why this is safe). Hokusai’s scheduler limits how many evaluations run at once, so spawning more tasks than cores is safe. withoutEnlargement: truemeans a 500-pixel original is never blown up to 1280: the request returns the original size for that rung instead (guards). It uses a width only, so the aspect ratio is kept and nothing is cropped.- The results printed: 320 → 320 × 200 (4,058 bytes), 640 → 640 × 400 (9,290 bytes), 1280 → 1280 × 800 (20,308 bytes).
Variations
Section titled “Variations”- Square thumbnails:
resize(width: 320, height: 320, fit: .cover, position: .attention); withwithoutEnlargementon a small source this combination throws, so usefit: .insideor checkmetadata()first (the pitfall). - Two formats: add
.jpeg(quality: 82)outputs from the same branches for browsers without WebP. - Streaming to storage: use
data()per rung and upload the bytes, orwriteChunksfor large outputs. - Memory-bound services: set
RuntimeConfiguration.maxConcurrentEvaluations(Runtime).