Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize images in directory using multiple CPU cores

I have several PNG images in a directory and I'm using optipng to optimize and reduce image size. The problem is that it takes too long to optimize all files.

I have a quad core processor and I noticed that optipng was using only a single core when I optimize the directory.

This is the code I'm using:

ls -1 | while read line
do 
    optipng -o7 "$line"
done

Is it possible to execute optipng for four different files in parallel while reading a directory?

like image 965
Niresh Avatar asked Feb 15 '14 17:02

Niresh


2 Answers

There is another solution involving xargs.

find some/dir/ -iname '*.png' -print0 | xargs -0 -n 1 -P 4 optipng -o7

Where -P 4 launches 4 parallel processes and -n 1 uses at most one filename per process.

Alternatively, if you have newline-separated filenames, use:

find some/dir/ -iname '*.png' | sort | xargs -d \\n -n 1 -P 4 optipng -o7

Thanks to Joe Lencioni comment on a blog.


Update: I've written a shell script to call zopflipng (which gives a higher compression than optipng) for several images in parallel: zopflipng_in_place

like image 166
Denilson Sá Maia Avatar answered Oct 26 '22 12:10

Denilson Sá Maia


I use optipng with GNU parallel (included in every linux distribution):

parallel --bar 'optipng {}' ::: file1.png file2.png morefile*.png

The advantage: You have a bar indicating the progress.

like image 5
erik Avatar answered Oct 26 '22 14:10

erik