Skip to content

Instantly share code, notes, and snippets.

@fiee
Created April 5, 2012 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fiee/2311905 to your computer and use it in GitHub Desktop.
Save fiee/2311905 to your computer and use it in GitHub Desktop.
use imagemagick to crop a picture to a fixed size
#!/bin/bash
# ~/croptest is our work dir, ~/croptest/img contains test images
cd ~/croptest
EXT="_resized"
SIZES="88x88 88x50 300x172 300x233 300x111"
# delete all remains of previous runs and copy test pics over
rm *.jpg
cp img/*.jpg ./
for SIZE in $SIZES; do
for IMG in img/*.jpg; do
IMG=${IMG/img\//}
OUT=${IMG/.jpg/_${SIZE}.jpg}
# get image size
IMG_W=`identify -ping -format '%w' $IMG`
IMG_H=`identify -ping -format '%h' $IMG`
if [ $IMG_W -le $IMG_H ]; then
## portrait or square, crop from upper third
TGT_SIZE=(${SIZE//x/ })
#TGT_W=${TGT_SIZE[0]}
TGT_H=${TGT_SIZE[1]}
## just scale and calculate with new sizes
convert $IMG -fuzz 1% -trim +repage -resize ${SIZE}^ ${OUT}
#IMG_W=`identify -ping -format '%w' $OUT`
IMG_H=`identify -ping -format '%h' $OUT`
REST_H=$(( $IMG_H - $TGT_H ))
TOP_OFFSET=$(( $REST_H / 3 ))
## now crop
#echo "$IMG is portrait, resized as $SIZE = (${IMG_W}x${IMG_H}) top crop: $TOP_OFFSET"
convert ${OUT} -crop ${SIZE}+0+${TOP_OFFSET} +repage ${OUT}
else
## landscape
convert $IMG -fuzz 1% -trim +repage -resize ${SIZE}^ -gravity center -extent ${SIZE} ${OUT}
fi
#OFFSET_TOP = identify -ping -format '%[fx:(h-233)/3]' $IMG
## see http://www.imagemagick.org/script/fx.php
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment