Ade Malsasa Akbar contact
Senior author, Open Source enthusiast.
Saturday, July 30, 2016 at 12:01

This short tutorial shows how to convert multiple files from PNG to JPEG format (and vice versa) using ImageMagick command lines and bash looping. Including explanation to make it easier to understand. This is much more easier than doing it manually one by one.

1. PNG to JPEG

 

for i in *.png; do convert -verbose "$i" "`echo $i | sed 's/.png/.jpeg/g'`"; done


2. JPEG to PNG


for i in *.jpeg; do convert -verbose "$i" "`echo $i | sed 's/.jpeg/.png/g'`"; done


Sample Output

PNG to JPEG

JPEG to PNG

The Files

Explanation


The actual single command (non-looping) for ImageMagick's convert will be like this: convert picture.png convert.jpeg to convert PNG to JPEG. If we want to do this conversion in bulk, then we need some modification. We we modify it by using bash looping in combination with sed. See the steps below.

(1) Both commands are actually simple. They are basically templates of bash shell looping to read every file name in current directory and save every name to variable `i`:

for i in *.png; do [COMMAND]; done

(2) and we replace the bash looping [COMMAND] with the actual ImageMagick's convert command line:

convert [FILE1] [FILE2] 


(3) but we modify the first convert's [FILE1] argument with $i to represent the file name to be converted which has been saved before:


convert "$i" [FILE2]


(4) and we modify the second convert's [FILE2] argument with the file name modificator command line, a combination from echo and sed:

convert "$i" "`echo $i | sed 's/.png/.jpeg/g'`"

(5) and finally bash do that 1-4 jobs for one png file and continue the next png file and continue the next png file until all png files converted successfully. This is the looping. There, sed makes the extension file name .png to be changed into .jpeg (by the help from echo). To help you understand sed more, we prepared GNU sed command lines examples Episode 5.

The similar happens with the JPEG to PNG conversion.