像PageSpeed那样优化/无损压缩图像

时间:2012-10-21 20:03:56

标签: php

我按如下方式压缩JPEG图像:

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 <= $max_width && $height <= $max_height) {
        $tn_width = $width;
        $tn_height = $height;
        } elseif ($x_ratio * $height < $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);
}

问题在于我总是得到比PageSpeed建议的图像大一点的图像。

例如,对于尺寸为8.85KB的图像,PageSpeed建议我可以将此尺寸缩小356B。

如何压缩图像并使其尽可能小?为了使PageSpeed不提出任何建议并得到100分。

1 个答案:

答案 0 :(得分:1)

压缩只会损害质量。音乐和视频也一样。

val dateRanges : Array[(String,String)]= Array(("2005-01-01","2005-12-31"), 
                                               ("2006-01-01","2006-12-31"))
dateRanges.foreach(//execute your method here)