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

4
  • 1
    Do you want to keep the original files? Commented Apr 17, 2017 at 20:16
  • Nope - happy for them to be deleted Commented Apr 17, 2017 at 20:20
  • 1
    Do you trust file to determine the format? Commented Aug 30, 2017 at 18:34
  • identify would be safer for determining the image format (if I remember correctly, it was a decade since I used ImageMagick). Commented Aug 30, 2017 at 19:07

2 Answers 2

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.

1
  • :) 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. Commented Apr 18, 2017 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 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.