Skip to content
Hokusai2.2.2
ivantokar.com

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")
}
}
  • The landscape at 320 by 200 pixels.
    320 · 4.1 KBWEBP · 320 × 200 · 4 KB
  • The landscape at 640 by 400 pixels.
    640 · 9.3 KBWEBP · 640 × 400 · 9 KB
  • The landscape at 1280 by 800 pixels.
    1280 · 20.3 KBWEBP · 1280 × 800 · 20 KB
  • A pipeline is immutable, so one source can 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: true means 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).
  • Square thumbnails: resize(width: 320, height: 320, fit: .cover, position: .attention); with withoutEnlargement on a small source this combination throws, so use fit: .inside or check metadata() 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, or writeChunks for large outputs.
  • Memory-bound services: set RuntimeConfiguration.maxConcurrentEvaluations (Runtime).