24

I want to rotate all the images in a directory that match a pattern.

So far I have:

for file in `ls /tmp/p/DSC*.JPG`; do
  convert $file -rotate 90 file+'_rotated'.JPG
done

but that gives no output?

Max N
  • 226
  • 2
  • 11
Michael Durrant
  • 41,213
  • 69
  • 165
  • 232

7 Answers7

26

mogrify -rotate 90 *.jpg The better One-Liner for rotating all images with imagemagick

mogrify -rotate 90 /tmp/p/DSC*.JPG will infact rotate all .JPG beginning with DSC in the p directory

Mogrify (part of imagemagick) differs from Convert in that it modifies the original file http://www.imagemagick.org/script/mogrify.php

Alex
  • 261
  • 3
  • 2
  • 1
    Not true. Mogrify "is similar to magick convert except that the original image file is overwritten (unless you change the file suffix with the -format option) with any changes you request". – KeyC0de Apr 30 '20 at 12:43
23

There are quite a few issues with your code. First of all, you are parsing ls which is a Bad Idea. You also need to refer to the variable as $file as you point out and you should also quote it so it won't break on spaces. You are declaring num but it is never used. A safer way would be:

find /tmp/p/ -name "DSC*.JPG" | while IFS= read -r file; do
  convert "$file" -rotate 90 "$file"_rotated.JPG
done

This will still have problems if your files contain newlines but at least will not break if your path contains spaces.

If the files are all in the same directory, it can be further simplified using globbing. You can also use parameter expansion to create foo_rotated.JPG1 instead of foo.JPG_rotated.JPG:

for file in /tmp/p/DSC*.JPG; do
  convert "$file" -rotate 90 "${file%.JPG}"_rotated.JPG
done
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
terdon
  • 234,489
  • 66
  • 447
  • 667
11

A simple method using PE (Parameter Expansion) is

for f in /tmp/p/DSC*.JPG
do
  convert -rotate 90 "$f" "${f%.JPG}"_converted.JPG
done
Valentin Bajrami
  • 9,244
  • 3
  • 25
  • 38
7

Not an imagemagic solution, but

sips -r 90 *.JPG

will rotate all images ending in .JPG 90 degrees. It's a good one liner.

desk_object
  • 71
  • 1
  • 1
6

Do not parse ls and the ls is not required here. Furthermore, you should quote your variables in case they contain spaces.

for file in *.JPG; do
  convert -rotate 90 "$file" rotated_"$file"
done
Marco
  • 33,188
  • 10
  • 112
  • 146
0

You can copy/paste this code in ubuntu, and save it as "rotate.sh"

#!/bin/bash -e

CUR_DIR=`pwd`
cd "${1}"

for file in *.jpg; do
    convert "${file}" -rotate 90 "${file}";
done

cd CUR_DIR

After saving this file, run it from terminal using ./rotate.sh folder_containing_images

ddnomad
  • 1,928
  • 2
  • 15
  • 31
vin
  • 1
0

I needed to refer to the file as $file, i.e.

for file in `ls /tmp/p/DSC*.JPG`; do
  convert $file -rotate 90 $file+'_rotated'.JPG
done
Michael Durrant
  • 41,213
  • 69
  • 165
  • 232