Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch crop and resize images to create thumbnails

I have a large set of jpg images for which I want to create thumbnails. The images all have different sizes and resolutions, but I would like all thumbnails to have a standard size, e.g. 120x80px. However, I do not want to stretch the images. So I would like to do something of the following:

  1. Crop image to a 1.5 : 1 aspect ratio. Center the cropping area (i.e. cut off an equal amount left and right, or above and below
  2. Resize the image to 120 x 80 px.

Is there a linux command to do so? I looked into imagemick convert, but I can't figure out how to do the centered cropping. It seems that you have to manually specify the cropping area for each image?

like image 908
Jeroen Ooms Avatar asked Dec 05 '12 23:12

Jeroen Ooms


1 Answers

This works for images larger than 120x80. Not tested on smaller ones, but you should be able to tune it.

#! /bin/bash
for img in p*.jpg ; do
    identify=$(identify "$img")
    [[ $identify =~ ([0-9]+)x([0-9]+) ]] || \
        { echo Cannot get size >&2 ; continue ; }
    width=${BASH_REMATCH[1]}
    height=${BASH_REMATCH[2]}
    let good_width=height+height/2

    if (( width < good_width )) ; then # crop horizontally
        let new_height=width*2/3
        new_width=$width
        let top='(height-new_height)/2'
        left=0

    elif (( width != good_width )) ; then # crop vertically
        let new_width=height*3/2
        new_height=$height
        let left='(width-new_width)/2'
        top=0
    fi

    convert "$img" -crop "$new_width"x$new_height+$left+$top -resize 120x80 thumb-"$img"
done
like image 139
choroba Avatar answered Sep 28 '22 17:09

choroba