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

GAD3R
  • 63,407
  • 31
  • 131
  • 192
pee2pee
  • 183
  • 2
  • 6

2 Answers2

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.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Dario
  • 401
  • 4
  • 7
  • :) 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 09: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
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501