Marcel
Marcel

Reputation: 57

imagemagick trim but keep canvas size and *position*

Friends,

I need to -trim some images but keep the original canvas size. Works like this:

convert in.png -fuzz 10% -trim -background white -set page "%[fx:w]x%[fx:h]" +repage out.png

But how can I position the trimmed image part at it's original position? -gravitiy center is not an option as the to-be-trimmed part usually not at the canvas center.

Any ideas?

Upvotes: 2

Views: 368

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207465

@GeeMack's answer is certainly simpler and more succinct, but if you need more flexibility for dinking around, another way is to get the image height and width and the trimbox in one invocation and use them in the next - maybe with adaptation.

So, starting with this image:

enter image description here

# Get image width and height and the trim-box
read geom trim < <(magick start.png -format "%G %@"  info:)

# Make a new white canvas same size as original and trim new image onto it
magick -size $geom xc:white \( start.png -crop $trim \) -flatten  result.png

enter image description here

I put an artificial yellow border around it so you can see the extent of it on SO's white background.

Upvotes: 2

GeeMack
GeeMack

Reputation: 5395

You should be able to -trim an image, then use -flatten to lay it back onto its original canvas. Try this command...

convert logo: -background none -trim -flatten trimmed.png

Upvotes: 3

Related Questions