Last Updated: February 25, 2016
·
1.362K
· asbigger

Resample Image to Size in Pixels With ImageMagick

Resizing to a maximum size in pixels can be tricky. I used to do this with a spreadsheet or a calculator, then I discovered the wonder of ImageMagick!

By passing this bash script 2 arguments (path to directory and size in pixels):

my_image_resizer.sh path/to/directory 1900000

You can resample an entire directory of images in no time!

#!/bin/bash

dir=$1
let max=$2 # target size in pixels

cd $dir

for file in `ls $dir`
do

  echo "Looking at '$file'"

  geometry=`identify '$file' | awk '{print $3}'` 
  width=`echo $geometry | sed 's/[^0-9]/ /g' | awk '{print $1}'`
  height=`echo $geometry | sed 's/[^0-9]/ /g' | awk '{print $2}'`

  let pix=$width*$height

  if [ $pix -gt $max ]; then

  echo "Resizing '$file'"
  mogrify "$file" -sample @$max "$file"

  fi

done

2 Responses
Add your response

You could use the -format option on identify to simplify getting the width and height.

Identify -format "%w %h" '$file'
over 1 year ago ·

I just went through this recently. Check it out:

for file in /path/to/files/*/*.jpg; do sudo convert $file -resize '480000@>' -density 72 $file; done

480000 = 800*600 so all images will have the same image area without killing files that are 1200x200 or something ridiculous like that.

https://gist.github.com/MikeNGarrett/9774888

over 1 year ago ·