Imagine you need to make changes to thousands or millions of images. You might write a simple script or batch process to handle the conversion automatically with ImageMagick. Everything is going fine, until you realize this process will take more time than expected.

After rethinking the process, you realize this task is taking so long because the serial method processes one image at a time. With that in mind, you want to modify your task to work in parallel. How can you do this without reinventing the wheel? The answer is simple: use GNU Parallel and the ImageMagick utility suite.

About GNU Parallel and ImageMagick

The GNU Parallel program can be used to execute jobs faster. If you use xargs or tee, you’ll find parallel easy to use. It’s written to have the same options as xargs. If you write loops in the shell, you’ll find parallel can often replace most of the loops and finish the work faster, by running several jobs in parallel.

The ImageMagick suite of tools offers many ways to change or manipulate images. It can deal with lots of popular formats, such as JPEG, PNG, GIF, and more.

The mogrify command is part of this suite. You can use it to resize an image, blur, crop, despeckle, dither, draw on, flip, join, re-sample, and much more.

Using parallel with mogrify

These packages are available in the Fedora repositories. To install, use the sudo command with dnf:

sudo dnf install ImageMagick parallel

Before you start running the commands below, be aware the mogrify command overwrites the original image file. If you want to keep the original image, use the convert command (also part of ImageMagick) to write to a different image file. Or copy your originals to a new location before you mogrify them.

Try this one-line script to resize all your JPEG images to half their original size:

cd ~/Pictures; find . -type f | egrep "*.jpg" | parallel mogrify -resize 50% {}

If you wanted to convert these files instead, adding -new to the filename:

cd ~/Pictures; find . -type f | egrep "*.jpg" | parallel convert -resize 50% {} {.}-new.jpg

Resize all your JPEG images to a maximum dimension of 960×600:

cd ~/Pictures; find . -type f -iname "*.jpg" | parallel mogrify -resize 960x600 {}

Convert all your JPEG images to PNG format:

cd ~/Pictures; find . -type f | egrep "*.jpg" | parallel mogrify -format png {/}

For more information about the mogrify command and examples of usage, refer to this link. Enjoy!


Photo by John Salzarulo on Unsplash.