PHP – Optimize your JPEG images with ImageMagick

If you need to optimize the images for your existing website, the following code might be useful:

 $dir = '/home/some_directory/'; // the directory with your files
 $compr = 80; // the quality precentage

 if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
     $path = $dir.$file;
     if (is_file($path)) {
       $ext = pathinfo($path, PATHINFO_EXTENSION);
       if (preg_match('/^(jpg|jpeg)$/i', $ext)) {
       exec(sprintf('convert %s -quality %d %s', $path, $compr, $path));

Just enter the path to the the directory you like to optimize safe the code as a PHP script and execute the file from the command line of browser.
Optimize your images top make them load faster, but be careful don’t compress them too much.

Leave a Reply

Your email address will not be published. Required fields are marked *