Skip to content

Instantly share code, notes, and snippets.

@kian
Last active January 21, 2016 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kian/c17025078067d9a3a4c4 to your computer and use it in GitHub Desktop.
Save kian/c17025078067d9a3a4c4 to your computer and use it in GitHub Desktop.
--omg-optimized
<?php
private function predictQualityForFilesize($width, $height, $bytes)
{
/*
* There's apparently some overhead in the JPEG file format that
* scales with the square root of the file's size. Accounting for it
* causes the bpp-to-quality curves for the different dimensions to
* line up better.
*
* I still don't know what it actually is.
*/
$bits = $bytes*8;
$adjustedBits = max($bits - 78.4*sqrt($bits), 0);
$pixels = $width*$height;
$adjustedBpp = $adjustedBits/$pixels;
// Generalized logistic curve, fitted to the median bpp/quality curves
// of 450 creatives (50/dimension) randomly sampled from production
// and compressed to all 100 different quality settings
list($lower, $upper) = [1, 100];
$quality = $lower +
($upper - $lower) / pow(1 - 18.0*exp(-1.44*$adjustedBpp - 3.85), -6.31);
/*
* Err on the side of suggesting too much compression.
*
* This is because we want to minimize the number of times an image is
* compressed: if we suggested too *little* compression, then STW would
* send us an image that was too big, and we would have to compress it
* again.
*
* Extra compressions are worth avoiding because each compression adds
* noise to the image. In fact, a single compression to a lower quality
* (e.g., 100% -> 65%) can look *better* than a double compression to
* a higher quality (100% -> 75% -> 70%).
*/
$quality -= 5;
// Clean up the result
$quality = (int) round($quality);
$quality = min($quality, 95); // In case the math above fails: don't suggest a
$quality = max(40, $quality); // quality setting that's too wasteful or too stingy
return $quality;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment