Skip to content
Hokusai2.2.2
ivantokar.com

Trim and extend

trim removes a border of nearly uniform colour, using the top-left pixel at that point of the pipeline as the background. extend adds canvas. Their order decides whether the padding survives.

let emblem = try Hokusai(url: URL(fileURLWithPath: "emblem.png")).resize(width: 160).flatten(background: .white)
// Pad, then trim: trim removes the padding it just got, because it matches the top-left pixel.
let padThenTrim = try emblem.extend(top: 30, left: 30, bottom: 30, right: 30,
mode: .background(.white)).trim()
// Trim, then pad: the padding is added after the border is gone, so it stays.
let trimThenPad = try emblem.trim().extend(top: 30, left: 30, bottom: 30, right: 30,
mode: .background(.white))
for (name, pipeline) in [("pad-then-trim", padThenTrim), ("trim-then-pad", trimThenPad)] {
let output = try await pipeline.png().data()
print(name, "→", output.info.width, "×", output.info.height)
try output.data.write(to: URL(fileURLWithPath: "\(name).png"))
}
  • The emblem at its original 160 pixel size: the padding was trimmed away again.
    extend → trimPNG · 160 × 160 · 7 KB
  • The emblem with 30 pixels of white padding all round, 220 pixels square.
    trim → extendPNG · 220 × 220 · 8 KB
Order Size Why
extend(30) then trim() 160 × 160 The white padding matches the top-left pixel, so trim removes it
trim() then extend(30) 220 × 220 There was nothing to trim (the emblem touches all four edges), then padding is added and stays

To normalise logos or screenshots with arbitrary borders to an exact padded size, trim first and extend last. If you extend with a colour that matches the image’s border, a later trim will undo it.