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"))
rotate → flattenJPEG · 219 × 219 · 11 KB 
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
rotatecreated 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.