Setting the compression level in Imagick automatically for maximum file size

I get the size of the images as they load. Imagick:

$im->getImageSize(); 

This returns the size in bytes of the image.

I would like to set the compression level automatically so that the file size never exceeds a certain size. If I wanted to limit it to 70 kb with a minimum acceptable compression level of 60 (on a scale from 0 to 100), I would start to do something like this:

  public function getCompLevel($size) { $maxsize = 70000; // Set rough max size of file $mincomp = 60; // Set minimum compression level allowed if($size > $maxsize ){ // If file size exceeds max allowed size, perform calculation $comp = **EQUATION** } return ($comp < $mincomp) ? $mincomp : $comp; // if output is less than minimum allowed compression , return minimum. If not return calculated compression level } 

What I'm trying to understand is the equation needed to calculate a close approximation of the required compression level based on file size. I understand that this may not be so accurate due to colors affecting the file size, but I would like to get as close as possible.

Any help would be greatly appreciated.

+4
source share
1 answer

I like this question, although there really is no right answer. I have replicated multipule instances in which the variable $x will represent the file size starting at zero and will increase to double the maximum file size. In addition, I created the $equalizer variable. This variable works exponentially, while setting it to 100 will create a higher compression level, and, conversely, closer to 0 will create a much larger gap.

 <?php $max_file_size = 70000; $max_compression = 60; $equalizer = 100; for($x=0;$x<$max_file_size+$max_file_size;$x+=10000){ if($x < $max_file_size){ echo $max_compression.'<br>'; }else{ echo $max_compression - (($x / $max_compression * $max_file_size) / ($max_file_size * $max_compression * $equalizer)).'<br>'; } }?> 

In your real situation, I would suggest that your function looks something like this:

 <?php function getCompLevel($size){ $maxsize = 70000; $compression = 60; $equalizer = 100; if($size > $maxsize ){ $compression = $compression - (($size / $compression * $maxsize) / ($maxsize * $compression * $equalizer)); } return $compression; }?> 
+2
source

All Articles