Trimming two sides of an image

I had a task to trim two sides of an image in script using Imagemagick. If you were working with command-line Imagemagick, then you surely know perfect examples of its use. There is an instruction how to trim one side of the image. Expanding this example we can create the following command to trim bottom and right borders:

convert image.png -background white -splice 0x1 -background black -splice 0x1 -trim +repage -chop 0x1 -background white -splice 1x0 -background black -splice 1x0 -trim +repage -chop 1x0 trim.png

It works nicely, but if you know background color of your image, you can simplify command. Let’s assume that we want to trim white background. Just add one black dot in top left corner, trim the image and chop image by one pixel from left and top:

convert -background white xc:black -size 1x1 -page +1+1 image.png -mosaic -trim +repage -chop 1x1 trim.png

Tags:

AddThis Social Bookmark Button

Leave a Reply