You can use ImageMagick's -trim
operator to obatin a similar result to Gimp's auto-crop, and then use ImageMagick's identify
command with a format to extract width and height as numbers:
With your image
$convert TrimSource.png -verbose -trim TrimTarget.png
TrimSource.png=>TrimTarget.png PNG 400x300=>315x201 400x300+29+67 8-bit sRGB 45495B 0.070u 0:00.027
And the output image is indeed 315 × 201 px, and its top right corner is indeed the pixel at (29,67) it the original image.
If you don't care for the output image, you can use a slightly different form to get the output on stdout and then discard it ("BMP" stands for any format (PNG/JPG also work...), just use one that doesn't use inordinate amounts of CPU for an image that will be tossed anyway):
$convert TrimSource.png -verbose -trim BMP:- >/dev/null
TrimSource.png=>- PNG 400x300=>315x201 400x300+29+67 8-bit sRGB 254070B 0.000u 0:00.002
On more recent versions of IM, use magick [convert]
instead of just convert
. How to extract data from the output is left as an exercise to the reader (depends on your shell language, fairly easy in bash, if that's your target, as in comments I can work it out for you).
Edit: Done for bash:
#! /bin/bash
# Trick command to dump the image to /dev/null and reroute stderr to stdout
out=$( convert $1 -verbose -trim BMP:- 2>&1 >/dev/null )
# Regex to catch the relevant bits from an output like:
# TrimSource.png=>- PNG 400x300=>315x201 400x300+29+67 8-bit sRGB 254070B 0.030u 0:00.010
if [[ $out =~ '=>'([0-9]+)x([0-9]+)' '[0-9]+x[0-9]+'+'([0-9]+)'+'([0-9]+)' ' ]]
then
# If regex matched then the groups in parentheses are in the BASH_REMATCH array
w=${BASH_REMATCH[1]}
h=${BASH_REMATCH[2]}
x=${BASH_REMATCH[3]}
y=${BASH_REMATCH[4]}
printf "Trimmed to %d*%d from (%d,%d)\n" $w $h $x $y
else
printf "Not recognized: %s\n" "$out"
fi