Auto-crop maintaining square canvas?

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
marcusj

Auto-crop maintaining square canvas?

Post by marcusj »

Hi

The -trim operator works well on my transparent-background PNG.

convert foo.png -trim bar.png.

Magick, indeed...

What I'm stuck on is maintaining a square canvas. That is to say, without resorting to scripting such as PerlMagick, I'd like the final image to have a square transparent canvas. FYI, the input image (foo.png) always has a square canvas and the output canvas could be anything, just smaller and almost always not square aspect ratio.

What I'd like to do is have the output image centred in a square, transparent canvas that's got the same pixel dimensions as the longest side (be it x or y) that is the result of the original trim.

I think it's got something to do with making a new, square transparent canvas that's got dimensions of the longest side of bar.png and then compositing bar.png onto that new canvas with a centre gravity. My problem is, without scripting, is how to make that new, square, transparent canvas to accommodate bar.png?

Thanks in advance.

Marcus
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Auto-crop maintaining square canvas?

Post by fmw42 »

Here is a set of commands. But you would likely need to script them.


convert hex10.png -fuzz 10% -trim +repage hex10_trim.png // trim
width=`identify -format %w hex10_trim.png` // get width of trimmed image
height=`identify -format %h hex10_trim.png` // get height of trimmed image
[ $width -gt $height ] && dim=$width || dim=$height // find larger of width or height
convert \( -size ${dim}x${dim} xc:none \) hex10_trim.png -gravity center -composite hex10_trim_canvas.png
// create square transparent image of largest dimension of trimmed image, center trimmed image in
// transparent background

The image hex10.png was created similar to the last colored hexagon tile pattern on
http://www.imagemagick.org/Usage/canvas/#pattern
but with size 260x210 and then a 10 pixel white border was added using

convert hexagons_260_210.png -bordercolor white -border 10x10 hex10.png


You might also want to look at my script autotrim at

http://www.fmwconcepts.com/imagemagick/index.html

I could possibly modify the script to add the option to center the trimmed result (as above) into a transparent background image.
Post Reply