I've got a directory with thousands of image files, mostly JPG but some PNG. The files have no extension, they're just numbered. I need to convert all of them to JPG.

Using find I can get a list of all the files with their types, and from that I can use Imagemagick to convert from PNG to JPG by specifying their type:

convert png:10020 jpg:10020.jpg

But I'd like to do this as a batch across all the files. How can I pipe the output of find and convert all the PNG files to JPG?

find . -type f | while read IN; do
  if [ "x$(file -b --mime-type $IN)" = "ximage/png" ]; then
    convert png:$IN jpg:$IN.jpg;

Meaning of arguments:

  1. .
    Find in the current directory

  2. -type f
    Just find files, not directories/sockets/etc.

  3. while read IN; do
    Put each filename into the variable IN and run the loop on it.

  4. if [ "x$(file -b --mime-type $IN)" = "ximage/png" ]; then
    Check if the file is a PNG...

  5. convert png:$IN jpg:$IN.jpg;
    ...and if it is, convert it.

  6. fi; done;
    We are done!

I have tested it this time, and it works, converting a directory full of PNG's without the .png extension to JPG's.

  • I also suggest you use the -iname (ignore case) option in the case it's .PNG and not .png or even .PnG etc. – arielnmz Jul 12 '14 at 1:57
  • @arielnmz It seems that you are more familiar with find than I am. At the time you left the comment, my command wouldn't even run...I have it working now, though. – BenjiWiebe Jul 12 '14 at 2:03
  • That would be fine IF the files had extensions, but they don't. That's why the question was asking about using the file command to get the actual filetype, then to convert only those PNG images that are found. – Hibiscus Jul 12 '14 at 4:24
  • @Hibiscus OK, I will update my answer to reflect that. It will be hard, but not impossible. :) – BenjiWiebe Jul 12 '14 at 15:31
  • @Hibiscus The latest edit works for me. Try it and see if it works for you! – BenjiWiebe Jul 12 '14 at 15:41

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.