8

Have images in subfolders that need to be limited in size (720 max width or 1100 max height). Their filenames must be preserved. Started with:

for img in *.jpg; do filename=${img%.*}; convert -resize 720x1100\> "$filename.jpg" "$filename.jpg"; done 

which works within each directory, but have a lot of subfolders with these images. Tried find . -iname "*.jpg" -exec cat {} but it did not create a list as expected.

This also didn't work:

grep *.jpg | while read line ; do `for img in *.jpg; do filename=${img%.jpg}; convert -resize 720x1100\> "$filename.jpg" "$filename.jpg"`; done 

Neither did this:

find . -iname '*jpg' -print0 | while IFS= read -r -d $'\0' line; do convert -resize 720x1100\> $line; done

which gives me error message "convert: no images defined." And then:

find . -iname '*.jpg' -print0 | xargs -0 -I{} convert -resize 720x1100\> {}

gives me the same error message.

motorbaby
  • 634
  • 7
  • 18
  • If you are using Bash 4 then you can easily modify your first attempt to process all jpg files in the directory tree: `shopt -s globstar ; for img in **/*.jpg ; do ... ; done`. – pjh Nov 11 '16 at 18:47
  • Also tried `find . -type d -exec bash -c 'cd "$0" || exit; shopt -s nullglob; f=( *.jpg ); ((${#f[@]})) && echo convert -resize 640x1100\> "${f[@]}" "${f[@]}"' {} \;` based on http://stackoverflow.com/questions/23311384/execute-imagemagick-convert-in-subfolders-with-bash-script – motorbaby Nov 11 '16 at 19:05
  • I upgraded Bash and got convert: unable to open image `'**/*.jpg'`: No such file or directory. – motorbaby Nov 11 '16 at 19:12
  • Ah! I was missing a subdirectory level... This worked Thanks so much! – motorbaby Nov 11 '16 at 19:15

2 Answers2

9

It seems you're looking for simply this:

find /path/to/dir -name '*.jpg' -exec mogrify -resize 720x1100\> {} \;

In your examples, you strip the .jpg extension, and then you add it back. No need to strip at all, and that simplifies things a lot. Also, convert filename filename is really the same as mogrify filename. mogrify is part of ImageMagick, it's useful for modifying files in-place, overwriting the original file. convert is useful for creating new files, preserving originals.

janos
  • 120,954
  • 29
  • 226
  • 236
  • Thanks. I've had bad luck with mogrify in the past; hence, hesitant to use it. But this worked great and is exactly what I need. Thank you! – motorbaby Nov 11 '16 at 21:10
0

Since all of the subdirectories are two levels down, found this worked:

for img in **/*/*.jpg ; do filename=${img%.*}; convert -resize 720x1100\> "$filename.jpg" "$filename.jpg"; done

Thanks to @pjh for getting me started. This also worked:

shopt -s globstar ; for img in */*/*.jpg ; do filename=${img%.*}; convert -resize 720x1100\> "$filename.jpg" "$filename.jpg"; done

But I got the error message "-bash: shopt: globstar: invalid shell option name" but all of the images larger than specified were resized with filenames preserved.

motorbaby
  • 634
  • 7
  • 18