Skip to content
Hokusai2.2.2
ivantokar.com

Upload normalisation

Goal. Accept an image from a user and store a safe, consistent version: bounded input, upright pixels, at most 1600 px, no private metadata. Inputs: phone.jpg (sideways, with EXIF). Needs: Hokusai 2.2.2.

// Normalise an untrusted upload: bounded input, upright pixels, sane size, no private metadata.
func normalise(_ upload: Data) async throws -> Output {
try await Hokusai(
data: upload,
options: .init(failOn: .truncated, limits: .init(maxBytes: 20_000_000, maxPixels: 50_000_000))
)
.autoOrient()
.resize(width: 1600, height: 1600, fit: .inside, withoutEnlargement: true)
.webp(quality: 82)
.data() // default metadata policy: EXIF, XMP, IPTC removed
}
let phone = try Data(contentsOf: URL(fileURLWithPath: "phone.jpg"))
let output = try await normalise(phone)
let meta = try await Hokusai(data: output.data).metadata()
print("upload →", output.info.width, "×", output.info.height, output.info.format.rawValue,
"exif:", meta.exif?.count ?? 0, "bytes")
try output.data.write(to: URL(fileURLWithPath: "normalised.webp"))
do { _ = try await normalise(Data("not an image".utf8)) } catch { print("bad upload →", type(of: error)) }
  • The scene upright and 1600 by 1000 pixels, as a WebP.
    normalised.webpWEBP · 1600 × 1000 · 30 KB

The program printed upload → 1600 × 1000 webp exif: 0 bytes, and for a non-image upload a HokusaiError.

  1. InputOptions(failOn: .truncated, limits: …) bounds the input before pixel work: 20 MB of bytes and 50 megapixels here. Tighten these to your policy (limits).
  2. autoOrient() makes the pixels upright, so the stored size (1000 × 1600) no longer matters (why).
  3. resize(width: 1600, height: 1600, fit: .inside, withoutEnlargement: true) caps the long side at 1600 and never enlarges: a safe choice for unknown sizes, unlike .cover (guards).
  4. webp(quality: 82) and the default metadata policy drop EXIF, XMP and IPTC; the read-back showed 0 bytes of EXIF (metadata).
  5. Errors are typed: a bad upload throws HokusaiError from data(), not from the constructor. In a server, map it to 400/413/422 (troubleshooting).
  • Large bodies: use Hokusai(spooling:) so the upload is not held in memory (uploads).
  • Untrusted formats: turn on RuntimeConfiguration.blockUntrustedOperations to refuse PDF, SVG and similar loaders (runtime).
  • Keep the colour profile only: the default already does; use MetadataPolicy(exif: .remove, icc: .preserve) to be explicit.