PHP图片压缩等级测试与优化建议
本例详细探讨了PHP环境下实现图片压缩与优化的十种不同层级方法,旨在为开发者提供实用的参考方案。
近期发现一款基于PHP编写的图片压缩工具,支持从0到9共十个等级的调节。当设置为0级时,压缩幅度有限,但能有效避免图像失真;随着等级提升,清晰度逐渐下降。通常情况下,压缩后的文件体积可缩减至原始大小的50%,具备较高的压缩效率。
以下是用于执行PHP图片压缩的具体代码示例。
<?php
Header("Content-type: image/PNG");/*告诉IE浏览器你做的程序是张图片*/
$image = @imagecreatefrompng ("banner.png");
imagepng ($image,null,0); /*压缩等级0-9,压缩后9最小,1最大*/
imagedestroy ($image);
?>
测试用的原始图片大小为125KB,为了观察不同压缩参数下的具体表现,进行了如下记录。
imagepng($img,null,0); --> Size = 225K imagepng($img,null,1); --> Size = 85.9K imagepng($img,null,2); --> Size = 83.7K imagepng($img,null,3); --> Size = 80.9K imagepng($img,null,4); --> Size = 74.6K imagepng($img,null,5); --> Size = 73.8K imagepng($img,null,6); --> Size = 73K imagepng($img,null,7); --> Size = 72.4K imagepng($img,null,8); --> Size = 71K imagepng($img,null,9); --> Size = 70.6K
令人困惑的是,为何在压缩等级设为0时,生成的文件大小反而比原图更大?
在常规优化场景中,推荐使用等级2。此时图像质量无明显损失,而体积减少了30%,符合优化目标。若使用6、7、8或9等高压缩等级,图像会出现明显失真,因此不建议在此类场景下使用这些高数值进行优化。
关于这一现象,国外技术社区提供了以下解释:
The result seems accurate since 0 means no compression
quality Compression level: from 0 (no compression) to 9.
It's normal for the 0ed file to be larger than the original (that can be slightly compressed to begin with). You need to understand file compression and PHP GD image constructor.
上述解释是否合理?观点认为原始图片本身已经过轻微压缩,而等级0意味着不进行任何额外压缩处理,因此其体积可能大于已压缩的原图。这一说法具有一定的逻辑合理性。
希望本文所述内容能对各位在进行PHP程序设计时有所帮助。