📄 Crop image ⚡️
The snippet can be accessed without any authentication.
Authored by
Flavio Poletti
This program does a crop
the way I mean it: get an image as input, provide two diagonally opposed vertices, and produce an image from that rectangle.
The list of files to crop is provided in the standard input, so that this can be piped in the shell. There are two positional arguments: two points (in the x,y
form, like e.g. 19,72
) and an optional substitution suitable for sed
, to generate the name of the cropped file.
The names of cropped files are printed on standard output, for further processing down the line.
The cropped images are produced with +repage
, which means that there is no virtual canvas preserved and it just works.
crop 855 B
#!/bin/sh
if [ $# -lt 2 ] ; then
printf >&2 %s\\n "$0 <x1>,<y1> <x2>,<y2> [<substitution>]"
exit 1
fi
# these are the two extremes of the rectangle
p1="$1"
p2="$2"
# optionally take a substitution
substitution="${3:-"s/^/cropped-/"}"
# get x and y min and max positions
x1="${p1%%,*}"
y1="${p1##*,}"
x2="${p2%%,*}"
y2="${p2##*,}"
if [ "$x1" -gt "$x2" ] ; then
x="$x1"
x1="$x2"
x2="$x"
fi
if [ "$y1" -gt "$y2" ] ; then
y="$y1"
y1="$y2"
y2="$y"
fi
# calculate width and height. Both min and max have to be included
# hence the +1
dx=$((x2 - x1 + 1))
dy=$((y2 - y1 + 1))
# this is the "geometry" required by imagemagick
geometry="${dx}x${dy}+${x1}+${y1}"
while read input ; do
output="$(printf %s "$input" | sed -e "$substitution")"
convert "$input" -crop "$geometry" +repage "$output" >&2
printf %s\\n "$output"
done
Please register or sign in to comment