Search code examples
bashimagemagickidentify

Set all images to landscape with bash


In the file explorer or in shotwell some images appear to be in portrait mode some are in landscape. But the identify command can't differentiate them :

Landscape :

IMG_0064.JPG JPEG 3648x2736 3648x2736+0+0 8-bit DirectClass 3.319MB 0.000u 0:00.000

Portrait :

IMG_0108.JPG JPEG 3648x2736 3648x2736+0+0 8-bit DirectClass 3.004MB 0.000u 0:00.000

I use the following script to get the width and the height of my images :

Batch crop and resize images to create thumbnails

Is there a way to also get the orientation ?

------------------------------------------------------------------------------------------

What I wanted was to batch crop and resize images to create thumbnails (solution) and that if I get some portrait images in the pool it rotates them.

COMPLETE SOLUTION :

#! /bin/bash
for img in *.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

    orientation=$(identify -format '%[exif:orientation]' $img)
        if (( orientation > 1 )) ; then # crop horizontally
        echo "$img is portrait"
        name="temp"
        convert -rotate 90 "$img" "$name"
        mv "$img" "portrait_$img"
        mv "$name" "$img"
    fi

    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 -auto-orient "$img" -crop "$new_width"x$new_height+$left+$top -resize 120x80 thumb-"$img"
done

Solution

  • You can add the -auto-orient option to convert to rotate the images automatically.

    If you just need to get the orientation, you have to use a format specifier on identify, e.g.:

    identify -format '%[exif:orientation]' image_file.jpg
    

    For more details, see the section on Digital Photo Orientation in the ImageMagick documentation.