getButterfly Logo getButterfly

Let’s suppose you don’t use WordPress or another CMS that allows you to bulk optimize your JPEG images. Let’s suppose you have multiple folders and it’s nearly impossible to use an online optimizer due to directory restrictions or volume of work.

So, you create a PHP file called io.php and add the following code:

ini_set('memory_limit', '512M');
ini_set('max_execution_time', 600); // 10 minutes

$dir = "uploads/{*.jpg}";
// Open a known directory, and proceed to read its contents
$images = array();
foreach(glob($dir, GLOB_BRACE) as $key => $img) {
    echo 'Optimizing <b>' . $img . '</b>...<br>';
    $image = imagecreatefromjpeg($img);
    imagejpeg($image, $img, 60); // from 0 to 100 (percentage)

Save it, upload it to your site root using your FTP client and run it – After several minutes, the listing stops and all your images have been optimized.

The only variables you need to modify are the directory path (uploads in the code above) and the level of compression (usually 60 to 75 is the most common).

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a Reply

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