Search code examples
phpimagemagickimagemagick-convert

imagemagick trim the bottom from transparent PNG


I am attempting to write an imagemagick command to trim the transparent pixels from the bottom of a transparent PNG. I found these commands and modified them to take off just the bottom. However the output is not as expected.

With some trial and error I've identified that the command appears to be generating an image of a minimum height. If the design is too high it leaves transparent pixels underneath. But nothing jumps out at me as being the element of the command that causes that?

I've included my 3 files that I trimmed and the 3 results that the following command(s) generates:

convert \( ORIGINAL.png -bordercolor none -border 1x0 \) -size 1x1 xc:black -gravity west -composite -size 1x1 xc:black -gravity east -composite -size 1x1 xc:black -gravity north -composite -fuzz 10% -trim +repage -bordercolor white -shave 1x0 TRIMMED.png

convert \( ORIGINAL2.png -bordercolor none -border 1x0 \) -size 1x1 xc:black -gravity west -composite -size 1x1 xc:black -gravity east -composite -size 1x1 xc:black -gravity north -composite -fuzz 10% -trim +repage -bordercolor white -shave 1x0 TRIMMED2.png

convert \( ORIGINAL3.png -bordercolor none -border 1x0 \) -size 1x1 xc:black -gravity west -composite -size 1x1 xc:black -gravity east -composite -size 1x1 xc:black -gravity north -composite -fuzz 10% -trim +repage -bordercolor white -shave 1x0 TRIMMED3.png

If someone could please explain what I am missing in terms of this height issue that would be really appreciated.

These are the 3 ORIGINAL files and the 3 outcomes showing how the outcome changes with the original file changes.

This is what I am trying to acheive - delete the empty space from the bottom of the image. I want no space after the image at the moment if it is too high I still get space underneath (see the last outcome, bottom right)

---- BELOW ARE JUST THE ORIGINAL FILES IF ANYONE WANTED TO TRY IT ON THEIR SETUP ETC ----

My original attempt Here you can see lots of space

My second attempt Trimmed right to the bottom

My 3rd attempt Small gap leading me to beleive there is some minimum height coming from somewhere


Solution

  • If you're trying to remove what a "-trim" would remove, but only from the bottom edge of an image, this command should give you that result...

    convert input.png -background none -set page %[@] \
       -set option:distort:viewport %[w]x%[fx:page.y+page.height] \
       +repage -distort SRT 0 result.png                
    

    It starts by setting some variables that contain the results of a "-trim" operation, but without actually removing anything. Then it uses those variables to calculate the after-trim dimensions for the output viewport. Then it uses a no-op "-distort" to effectively crop the image to the calculated output dimensions, removing only the excess transparent pixels toward the bottom.