user9391457
user9391457

Reputation: 21

How to set specific compression in Kb using imagejpeg in php

I'm trying to compress uploaded images down to a specific size of 200Kb. I don't want to compress them any more than they need to be and using lossless compression like PNG isn't enough. Simply setting it to imagejpeg($image, null, 40) creates different compressed sizes for different images. Is there a way to set the desired compression size in bytes or at least have some algorithm that can find out the compression output without looping through imagejpeg() from 100 to 0 quality?

Upvotes: 0

Views: 619

Answers (2)

user9391457
user9391457

Reputation: 21

I found a way to use ob to view the file size of the image before it is uploaded so I used it in a loop

// Get get new image data
    ob_start();
    // Build image with minimal campression
    imagejpeg($newImage, NULL, 100);
    // Get the size of the image file in bytes
    $size = ob_get_length();
    // Save new image into a variable
    $compressedImage = addslashes(ob_get_contents());
    // Clear memory
    ob_end_clean();

    // If image is larger than 200Kb
    if ($size > 200000) {
      // This variable will decrease by 2 every loop to try most combinations 
      // from least compressed to most compressed
      $compressionValue = 100;
      for ($i=0; $i < 50; $i++) {
        $compressionValue = $compressionValue - 2;
        ob_start();
        imagejpeg($newImage, NULL, $compressionValue);
        $size = ob_get_length();
        // Overwrite old compressed image with the new compressed image
        $compressedImage = addslashes(ob_get_contents());
        // Clear memory
        ob_end_clean();
        // If image is less than or equal to 200.5Kb stop the loop
        if ($size <= 200500) {
          break;
        }
      }
    }

This is incredibly well optimized on its own too. The whole process only takes a few milliseconds with a 1.5Mb starting image even when it is trying 50 combinations.

Upvotes: 1

user3344003
user3344003

Reputation: 21607

There really isn't any way to predict the level of compression beforehand. The effect of compression depends upon the image source. One of the problems is that there is a myriad of JPEG compression settings.

  1. The quantization tables (up to 3) with 64 different values.
  2. Sub sampling.
  3. Spectral selection in progressive scans.
  4. Successive Approximation in progressive scans.
  5. Optimize huffman tables.

So there are billions upon billions of parameters that you can set.

There are JPEG optimization applications out there that will look at the compressed data.

Upvotes: 0

Related Questions