16
for parentDir in *
do
    cd "$parentDir"
    for subDir in *
    do
        cd "$subDir"
        for file in *.*
        do
            convert "$file" -crop 120x95 summary_"$file"
            convert "$file" -crop 160x225 detail_"$file"
        done
        mkdir detail
        mkdir summary
        mv summary_* summary/
        mv detail_* detail/
        cd ..
    done
cd ..
done

Here is my script, I need a way to crop the image without resizing, get rid of the extra surrounding.

For example: 1200* 1500 image ----> 120px * 90px from the center

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Andy Li
  • 277
  • 2
  • 3
  • 7

3 Answers3

35

If you are just trying to crop each image to one center part then use

convert input.suffix -gravity center -crop WxH+0+0 +repage output.suffix

Otherwise, you will get many WxH crops for each image.

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • Don't forget to add output_file at the end of the command. I forgot it and got misleading error debug so take time to figure it out. – chickensoup Aug 26 '19 at 08:34
  • in batches `for f in *.jpg; do convert "$f" -gravity center -crop 98x98+0+0 +repage "$f" ; done` – Ax_ Jun 20 '22 at 03:31
  • and fulfil with -extent in a canvas -background white `for f in *.jpg; do convert "$f" -gravity center -crop 98x98+0+0 +repage -extent 98x98 -background white "$f" ; done` – Ax_ Jun 20 '22 at 03:32
  • @Ax is that a question or suggestion. Adding -extent will depend upon what result is wanted. – fmw42 Jun 20 '22 at 04:52
1

Thanks to @fmw42 I've made this script to use with my file manager Dolphin, which can be adapted for others as well:

#!/usr/bin/env bash
# DEPENDS: imagemagick (inc. convert)
OLDIFS=$IFS
IFS="
"
# Get dimensions
WH="$(kdialog --title "Image Dimensions" --inputbox "Enter image width and height - e.g. 300x400:")"
# If no name was provided
if [ -z $WH ]
then
    exit 1
fi
for filename in "${@}"
do
    name=${filename%.*}
    ext=${filename##*.}
    convert "$filename" -gravity center -crop $WH+0+0 +repage "${name}"_cropped."${ext}"
done
IFS=$OLDIFS
Sadi
  • 111
  • 4
0

Enother imagemagick based solution. Here is a scrip version with mogrify to bulk images manipulation instead of convert which works on individual images:

for parentDir in *
do
  cd "$parentDir"
  for subDir in *
  do
    cd "$subDir"

    mkdir detail
    cp * detail/
    mogrify -gravity center -crop 160x225+0+0 +repage detail/*

    mkdir summary
    cp * summary/
    mogrify -gravity center -crop 120x95+0+0 +repage summary/*
  done
  cd ..
done
Ivan Kovtun
  • 645
  • 1
  • 11
  • 18