Search code examples
imagemagickimagemagick-convert

How to trim a png with ImageMagick convert tool, and keep all things same distance to original center?


I have a png with some transparency at board, and I want to trim the transparency, and keep every thing with same distance to the original center. I use convert tool from ImageMagick For example,

The original one.

The original

The result I want.

The correct result

The result I use with convert original.png -trim +repage out.png

The wrong result

The original file is here.

enter image description here


Solution

  • I can get your described result by using IM 6.8.9-9 in the ubuntu bash shell in Windows 10, running this command...

    convert test.png -write mpr:input -duplicate 3 \
       -distort SRT %[fx:t*90] -background none -layers merge -trim \
       -set option:pagewide %[w] -set option:pagehigh %[h] -set option:pageoffset %[fx:page.x] \
       -delete 0 mpr:input -set page %[pagewide]x%[pagehigh]-%[pageoffset]-%[pageoffset] \
       -coalesce result.png
    

    That reads in the input, stores one copy in temporary memory, makes 3 more copies of it, and rotates them 0, 90, 180, and 270 degrees. Then it flattens them and uses the trim results from that to calculate the final image dimensions and offsets. Next it deletes that modified image, brings the original back from temporary memory, and creates the output by applying those calculated page settings to the original.

    This should work with square images. If the width and height dimensions are not the same, the calculations would become more complicated.

    EDITED TO ADD: The command I've added below should take any input image and trim away as much transparent as possible while keeping the original center pixel(s) at the center of the result...

    convert test.png -write mpr:input -background none \
       -rotate 180 mpr:input -composite -set page %[@] \
       -set option:bounds %[fx:page.width]x%[fx:page.height]-%[fx:page.x]-%[fx:page.y] \
       -delete 0 mpr:input -set page %[bounds] -coalesce result.png
    

    It trims the same amount from the top and the bottom, and trims the same amount from the left and right, but the top/bottom amount may be different from the left/right amount.