Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop image from center without resizing with imagemagick

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

like image 522
Andy Li Avatar asked Oct 24 '16 18:10

Andy Li


People also ask

How do you crop on ImageMagick?

To crop an image using ImageMagick, you need to specify the X and Y coordinates of the top corner of the crop rectangle and the width and height of the crop rectangle. Use the mogrify command if you want the images to be replaced in-place or use the convert command otherwise to make a copy.

What is ImageMagick command?

ImageMagick includes a number of command-line utilities for manipulating images. Most of you are probably accustomed to editing images one at a time with a graphical user interface (GUI) with such programs as Gimp or Photoshop. However, a GUI is not always convenient.

What is ImageMagick Linux?

ImageMagick is a free and open source, feature-rich, text-based, and cross-platform image manipulation tool used to create, edit, compose or convert bitmap images. It runs on Linux, Windows, Mac Os X, iOS, Android OS, and many other operating systems.


2 Answers

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.

like image 92
fmw42 Avatar answered Sep 30 '22 11:09

fmw42


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
like image 25
Sadi Avatar answered Sep 30 '22 13:09

Sadi