Image formats: mass conversion on Linux

To convert a file from a image format to another, you can user the 'convert' command on Linux.

One of the common situation is to convert a large number of images. The firts attempt could be to combine convert and findcommands.

This code converts all the Jpeg images in the current directory into PNG.

 find *.jpg -exec convert \\{\\} \\{\\}.png \;

This fast-and-dirty solution has side effects because convert uses the extention to define the target image format. Indeed the converted files end with a double extention: the original one and the new one. So image01.jpg became image01.jpg.png.

To solve this, I wrote a simple script. You can copy and past the code in a file called mass_conv.sh:

 #!/bin/bash
 function usage () {
              echo "mass_conv -  mass image conversion"
              echo "Usage:"
              echo "       mass_conv.sh source_extension target_extension";
 }

 if [ "$#" == "2" ]; then
       for old_name in *.$1
       do
       new_name=`echo $old_name | sed s/.$1/.$2/`;
           convert $old_name $new_name
      done;
 else
      usage
 fi

The script uses the sed command to correctly rename the target file. Just an example: to convert all the Jpeg images into PNG format without double extention you can write: ./mass_conv.sh jpg png