3

I have a folder of images. All have the JPG extension but when running file against a few, they're coming back as bitmap e.g.

25818.jpg: PC bitmap, Windows 3.x format, 357 x 500 x 24

My question is how would I loop through all the images, check whether it's a bitmap file and then convert it to a JPG?

The command I'd use in a single case would be the following but not sure how I'd do the checks and loop through the files

mogrify -format jpg 25818.jpg

Thanks

  • 1
    Do you want to keep the original files? – Bruno9779 Apr 17 '17 at 20:16
  • Nope - happy for them to be deleted – pee2pee Apr 17 '17 at 20:20
  • 1
    Do you trust file to determine the format? – Kusalananda Aug 30 '17 at 18:34
  • identify would be safer for determining the image format (if I remember correctly, it was a decade since I used ImageMagick). – Kusalananda Aug 30 '17 at 19:07
3
while IFS='' read -rd '' filename; do 
  [[ $(file -b --mime-type "$filename") = image/x-ms-bmp ]] \
      && mogrify -format jpg "$filename"
done < <(LC_ALL=C find . -maxdepth 1 -name '*.jpg' -print0)

will work, provided that your version of file outputs image/x-ms-bmp when given a BMP file as argument of file -b --mime-type. Otherwise, you have to modify the script.

Many users would settle for the simpler version

for filename in ./*.jpg; do 
  [[ $(file -b --mime-type "$filename") = image/x-ms-bmp ]] \
      && mogrify -format jpg "$filename"
done

which, however, would fail in some circumstances: 1) if you have a very large number of files with very long names (say, 30000 filenames of average length) 2) if your filenames contain really weird characters.

The first version is guaranteed against such rare inconveniencies.

  • :) I wasn't chatting... I was simply suggesting you use find the right way, that is use the built-in -exec but I see you misread my comments. Never mind then. – don_crissti Apr 18 '17 at 9:52
1

With exiftool, you could do:

exiftool -q -r -ext jpg -if '
  $FileType eq "BMP" and !print "$Directory/$FileName\0"' . |
  xargs -r0 mogrify -format jpg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.