Optimize/losslessly compress images like the PageSpeed does
<p>I compress the JPEG images as below:</p>

<pre><code>function convert_img($img_source) {
    $img_destination = $img_source;
    $max_width = 150;
    $max_height = 150;
    $src = imagecreatefromjpeg($img_source);
    list($width,$height) = getimagesize($img_source);
    $x_ratio = $max_width/$width;
    $y_ratio = $max_height/$height;

    if ($width &lt;= $max_width &amp;&amp; $height &lt;= $max_height) {
        $tn_width = $width;
        $tn_height = $height;
        } elseif ($x_ratio * $height &lt; $max_height) {
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        } else {
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
    }

    $tmp = imagecreatetruecolor($tn_width,$tn_height);
    imagecopyresampled($tmp,$src,0,0,0,0,$tn_width,$tn_height,$width,$height);
    imagejpeg($tmp,$img_destination,80);
    imagedestroy($src);
    imagedestroy($tmp);
}
</code></pre>

<p>The problem is that I always get an image a little bit larger in size than PageSpeed suggests.</p>

<p>For example for an image with 8.85KB in size, PageSpeed suggests that I can reduce this size by 356B.</p>

<p>How do I compress my images and make them to have the smallest size possible? In order to make the PageSpeed to not suggest anything and to get 100 points.</p>
