Skip to content
Hokusai2.2.2
ivantokar.com

Flatten before JPEG

rotate by a non-right angle exposes new corners, transparent unless you give a background. JPEG cannot store transparency, so what those corners become depends on whether you flattened after the rotation.

let emblem = try Hokusai(url: URL(fileURLWithPath: "emblem.png")).resize(width: 160)
let paper = Color(red: 0.96, green: 0.94, blue: 0.88)
// A: rotate, then flatten: the exposed corners are painted with the paper colour.
let rotateThenFlatten = try emblem.rotate(by: 30).flatten(background: paper)
// B: flatten, then rotate: the new corners are transparent again, and JPEG turns them black.
let flattenThenRotate = try emblem.flatten(background: paper).rotate(by: 30)
try await rotateThenFlatten.jpeg(quality: 90).write(to: URL(fileURLWithPath: "rotate-then-flatten.jpg"))
try await flattenThenRotate.jpeg(quality: 90).write(to: URL(fileURLWithPath: "flatten-then-rotate.jpg"))
  • The emblem rotated 30 degrees and then flattened onto paper: the corners are paper-coloured.
    rotate → flattenJPEG · 219 × 219 · 11 KB
  • The emblem flattened first and then rotated: the new corners are black.
    flatten → rotateJPEG · 219 × 219 · 14 KB
  • rotate → flatten: the flatten sees the transparent corners and paints them with the paper colour.
  • flatten → rotate: the emblem had no transparency left to flatten, then rotate created new transparent corners that nothing resolves, and the JPEG encoder wrote them black (observed with libvips 8.18).

The rule is the one in Encoders: flatten last, immediately before a format without alpha. Alternatively give rotate the final background colour (rotate(by:background:)), which fills the corners during the rotation.