Juv*_*ius 12 php gd jpeg image-compression image-optimization
在Google Chrome中运行Page Speed时,建议优化/压缩图像.这些图像大多是由用户上传的,因此我需要在上传过程中对其进行优化.我发现用PHP优化jpeg图像就像使用以下GD功能:
getimagesize()
imagecreatefromjpeg()
imagejpeg()
Run Code Online (Sandbox Code Playgroud)
因为我上载后调整图像我已经通过这些功能,拉动图像,另外我用imagecopyresampled()后imagecreatefromjpeg()调整其大小.
但是,Page Speed仍然告诉我这些图像可以进行优化.如何在php脚本中完成此优化?在imagejpeg()中设置较低的质量也没有区别.
Pez*_*kow 15
imagejpeg函数是您分配质量的地方.如果您已经将其设置为适当的值,那么您几乎无能为力.
页面速度可能会认为超过一定大小的所有图像都"需要压缩",或许只是确保它们都合理(在高度/宽度方面)和压缩.
您可以在pagespeed文档http://code.google.com/speed/page-speed/docs/payload.html#CompressImages上找到有关页面速度和压缩建议的更多信息,其中介绍了一些适当压缩的技巧/工具.
我刚刚读了以下内容:
有几种工具可以对JPEG和PNG文件进行进一步的无损压缩,而不会影响图像质量.对于JPEG,我们建议使用jpegtran或jpegoptim(仅在Linux上可用;使用--strip-all选项运行).对于PNG,我们建议使用OptiPNG或PNGOUT.
所以也许(如果你真的想坚持谷歌的建议)你可以使用PHP exec在文件上传时运行其中一个工具.
要使用php进行压缩,请执行以下操作(听起来您已经这样做了):
$source_url图像在哪里,$destination_url是保存的位置,$quality是1到100之间的数字,选择使用多少jpeg压缩.
function compressImage($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
//save file
imagejpeg($image, $destination_url, $quality);
//return destination file
return $destination_url;
}
Run Code Online (Sandbox Code Playgroud)
修复功能:
function compressImage($source_url, $destination_url, $quality) {
//$quality :: 0 - 100
if( $destination_url == NULL || $destination_url == "" ) $destination_url = $source_url;
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg')
{
$image = imagecreatefromjpeg($source_url);
//save file
//ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
imagejpeg($image, $destination_url, $quality);
//Free up memory
imagedestroy($image);
}
elseif ($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($source_url);
imageAlphaBlending($image, true);
imageSaveAlpha($image, true);
/* chang to png quality */
$png_quality = 9 - round(($quality / 100 ) * 9 );
imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
//Free up memory
imagedestroy($image);
}else
return FALSE;
return $destination_url;
}
Run Code Online (Sandbox Code Playgroud)