A web page needs a WebP card and a PNG download. I want the same crop in both. When I designed Hokusai 2.0, my Swift library for image processing with libvips, I took an idea I liked from sharp: start with the photo and write the edits in the order you’d apply them. For these two files, I can stop the chain just after the crop.
import Foundation
import Hokusai
let photo = URL(fileURLWithPath: "photo.jpg")
let card = try Hokusai(url: photo)
.autoOrient()
.resize(width: 1200, height: 630, fit: .cover)
Phone photos can store their orientation in metadata, so I put autoOrient() before the resize. The 1200 × 630 frame then applies to the upright photo. With .cover, Hokusai keeps the proportions, fills the frame, and crops the excess around the center.
At this point photo.jpg can still be missing. The Swift struct behind card holds the file URL and a plan for those operations. Each edit returns a new value. Hokusai can already check the dimensions, though. Set the width to zero and resize throws right here.
Choosing the encoder
let web = try card.webp(quality: 82)
let download = try card.png()
let webOutput = try await web.data()
let pngOutput = try await download.data()
web and download each keep the crop from card with their own encoder settings. Quality 82 applies only to the WebP. In 2.0 I removed the old HokusaiImage type and the synchronous toBuffer and toFile methods. I can now pass card to another function and let that function choose how to encode it.
Each data() call submits its plan to Hokusai’s evaluation scheduler. If I leave the dimensions as written and point photo at a missing file, both encoder selections succeed. The error comes from web.data(), the first call that needs to open the JPEG.
Reading the JPEG
For a large JPEG, Hokusai can ask the decoder for a smaller image. It first accounts for the EXIF orientation and works out how large the photo must be to cover the 1200 × 630 frame before cropping. It tries decoder sizes in order: 1/8, 1/4, then 1/2 of each source dimension. It picks the first size whose width and height, rounded up to whole pixels, both meet the resize target. If none fits, it decodes at full resolution.
The PNG call submits the plan again. Both encoders inherit the framing, but the API makes no promise about reusing decoded pixels. If I delete the temporary JPEG as soon as the WebP is ready, the PNG call can fail. If my upload handler already has the bytes in memory, I can start with Hokusai(data:) and let it release the temporary file before either encoder runs.
