How can I trim whitespace from an image but keep some padding with imagemagick?
I tried the -trim
option but imagemagick crops down to the very edge of the content without leaving any padding.
Note, I don't want to add a border in some color but instead keep more of the original image.
magick in.jpg -fuzz 5% -trim out.jpg
This ImageMagick v7 command is in Windows CLI syntax. (A version for IMv6 is described below.) It will read the input image, calculate the results of a "-trim" operation, adjust that geometry to provide for wider spacing all around, then create the output using "-extent" with the calculated dimensions and offsets...
magick input1.jpg -set page "%[@]" ^
-set option:pad 0.15 ^
-set option:wide "%[fx:page.width+(page.x*pad*2)]" ^
-set option:high "%[fx:page.height+(page.y*pad*2)]" ^
-set option:padx "%[fx:page.x-(page.x*pad)]" ^
-set option:pady "%[fx:page.y-(page.y*pad)]" ^
-extent "%[wide]x%[high]+%[padx]+%[pady]" ^
+repage result1.png
Adjust the amount of extra space by changing the value of that "-set option:pad" variable. This is the result of running the above command on your example input image...
EDITED TO ADD: Nearly the same command can be made to work in ImageMagick v6 by applying those dimensions and offsets to a "-distort" viewport instead of using the "-extent" operation.
convert input1.jpg -set page "%[@]" ^
-set option:pad 0.15 ^
-set option:wide "%[fx:page.width+(page.x*pad*2)]" ^
-set option:high "%[fx:page.height+(page.y*pad*2)]" ^
-set option:padx "%[fx:page.x-(page.x*pad)]" ^
-set option:pady "%[fx:page.y-(page.y*pad)]" ^
-set option:distort:viewport "%[wide]x%[high]+%[padx]+%[pady]" ^
-distort SRT 0 ^
+repage resultv6.png
These commands can be easily converted to *nix shell commands by changing all the continued-line carets "^" to backslashes "\".
To use the commands in a Windows BAT script, double all the percent signs "%%".