Output terminals
A pipeline does nothing until a terminal runs. Terminals run the blocking native work off Swift’s cooperative executor, are async, and are where decode, pixel and encode errors are thrown. Cancelling the calling task stops the work and throws CancellationError; the pipeline stays valid and can be evaluated again.
| Terminal | Returns | Use it for |
|---|---|---|
data() |
Output (data, info) |
Bytes in memory: an HTTP body, a database column. Needs an encoder. |
write(to:) |
OutputInfo |
A file; written through a temporary file and renamed. |
writeChunks(chunkSize:_:) |
OutputInfo |
Streaming with backpressure. Needs an encoder. |
raw(_:premultiplied:background:) |
RawImage |
Pixels without encoding (Raw pixels). Must have no encoder selected. |
metadata() |
ImageMetadata |
The source’s header (Inspection). |
OutputInfo carries format, width, height, byteCount and, for PDF, pdf (pageCount, pageWidth, pageHeight).
let image = try Hokusai(url: URL(fileURLWithPath: "scene.png")).resize(width: 400)
// data(): bytes and facts about them. An encoder must be selected.let output = try await image.webp(quality: 80).data()print("data():", output.info.format.rawValue, output.info.width, "×", output.info.height, output.info.byteCount, "bytes")
// write(to:) infers the encoder from the extension only when none is selected...let inferred = try await image.write(to: URL(fileURLWithPath: "inferred.webp"))print("inferred:", inferred.format.rawValue)// ...an explicit encoder always wins, whatever the extension says.let explicit = try await image.png().write(to: URL(fileURLWithPath: "really-png.jpg"))print("explicit:", explicit.format.rawValue, "written to a .jpg name")
// writeChunks(): bounded, backpressured output for streaming.var chunks = 0, total = 0let streamed = try await image.jpeg().writeChunks(chunkSize: 4096) { chunk in chunks += 1; total += chunk.count}print("writeChunks:", chunks, "chunks,", total, "bytes, info says", streamed.byteCount)
// outputFormat is known before evaluation, e.g. to set a Content-Type first.print("outputFormat:", try image.avif().outputFormat?.rawValue ?? "none", "—", image.outputFormat?.rawValue ?? "none (no encoder)")
// Mistakes are typed errors.do { _ = try await image.data() } catch { print("no encoder →", error) }do { _ = try await image.write(to: URL(fileURLWithPath: "out.xyz")) } catch { print("unknown extension →", error) }Reading the results
Section titled “Reading the results”data()printed the format, size and byte count it produced.write(to:)infers the encoder from the extension only when you selected none (inferred.webpwas written as WebP). An explicit encoder always wins:png()with a.jpgname writes PNG data toreally-png.jpg, so choose a matching extension yourself.writeChunksdelivered 9,660 bytes in 3 chunks of at most 4,096 bytes, andOutputInfo.byteCountagreed. At mostchunkSize × 4bytes of encoded output are held in the hand-off, so a slow consumer slows encoding down instead of growing memory.chunkSizeis1…67,108,864(default 64 KiB). TIFF cannot be written forward-only, so it is encoded in memory first and then streamed. Ifconsumethrows, encoding stops and that error is thrown; after a failure or cancellation the consumer has received a partial stream and must discard it.outputFormatis known before evaluation (avif, andnilwhen no encoder is selected), so a server can setContent-Typebefore the first byte.
File output guarantees
Section titled “File output guarantees”write(to:) writes to a temporary file (.name.hokusai-…) in the destination directory and renames it over the destination only when the write finished, so a failed or cancelled write leaves an existing file exactly as it was and never leaves half an image. A replaced file keeps its permissions; a symbolic link stays a link and its target is replaced. A destination that is a file the pipeline reads (including through a symbolic link) is refused with invalidOption (“output URL”) before anything is written: write to a different file and replace the original yourself. A destination that cannot be opened or written throws HokusaiError.io with a .write operation and the system’s reason.
Errors
Section titled “Errors”| Situation | Result |
|---|---|
data() or writeChunks without an encoder |
invalidOption(name: "output format", …"call jpeg(), png(), webp(), avif(), pdf(), or encode(using:) before data()") |
write(to:) with an unknown extension and no encoder |
invalidOption(name: "output URL", …"use a supported image extension or select an encoder") |
write(to:) an .svg name |
unsupported: SVG is an input format, not an encoder |
raw with an encoder selected |
invalidOption(name: "raw", …): use data() for an encoded image |
Output over RuntimeConfiguration.maxOutputPixels |
resource (outputPixels), before any pixel is computed |
Where the encoder goes
Section titled “Where the encoder goes”The encoder is terminal configuration, not an image operation: jpeg(quality: 70).resize(width: 300) and resize(width: 300).jpeg(quality: 70) produce byte-identical output, and selecting a second encoder replaces the first (Order of operations).