Working with images on the command line can be incredibly efficient, especially when you need to process multiple files at once. This guide will show you how to convert image formats using two powerful and widely-used tools: ImageMagick and ffmpeg.
Using ImageMagick
ImageMagick is a suite of tools for image manipulation. The convert command is what we’ll use for format conversion.
First, make sure you have ImageMagick installed:
# For Debian/Ubuntu
sudo apt-get install imagemagick
# For Red Hat/CentOS
sudo yum install ImageMagick
Single File Conversion
To convert a single image from JPG to PNG:
convert image.jpg image.png
It’s that simple. convert automatically determines the formats from the file extensions.
Batch Conversion
To convert all PNG files in the current directory to JPG, you can use the mogrify command, which is also part of ImageMagick. Be careful, as mogrify overwrites the original files by default if you don’t specify a different output directory.
To convert all PNGs to JPGs in place:
mogrify -format jpg *.png
If you want to keep the original files, a for loop is a safer option:
for file in *.png; do
convert "$file" "${file%.*}.jpg"
done
This loop iterates over all PNG files, and for each file, it creates a new JPG file with the same name but a different extension.
Using ffmpeg
While ffmpeg is primarily a video processing tool, it’s also excellent for image conversion.
First, install ffmpeg:
# For Debian/Ubuntu
sudo apt install ffmpeg
# For Red Hat/CentOS
sudo yum install ffmpeg
To convert an image:
ffmpeg -i input.jpg output.png
Conclusion
Both ImageMagick and ffmpeg are powerful tools for command-line image manipulation. For most image conversion tasks, ImageMagick’s convert and mogrify commands are the most direct and easy to use. ffmpeg is a great alternative, especially if you are already using it for video processing. With these tools, you can automate your image conversion workflows and save a significant amount of time.