Search code examples
image-processingimagemagick

To limit '-trim' to a specific color


I try to understand how to limit -trim to a specific color. I tried

magick input.png -background yellow -trim +repage output.png
magick input.png -background #ffff00 -trim +repage output.png

and any of these commands removes yellow. But if the yellow is already removed, it removes red then. How it should be fixed?

enter image description here

That is, how to make it work that if there is no yellow at image's edges, the command should not trim anything?

enter image description here


Solution

  • You can limit it to some color by specifying the background color in Imagemagick along with a zero or small fuzz value. Here I need a few percent fuzz because the yellow and red are antialiased near the transition between yellow and red so that the yellow is not a constant yellow everywhere.

    Input:

    enter image description here

    magick image.png -alpha off -background "rgb(255,255,84)" -define trim:percent-background=0% -fuzz 5% -trim +repage x1.png
    

    enter image description here

    magick x1.png -alpha off -background "rgb(255,255,84)" -define trim:percent-background=0% -fuzz 5% -trim +repage x2.png
    

    enter image description here