我正在使用firebug页面速度实用程序,其中一个建议是压缩图像 - 所以我编写了以下代码来压缩图像
$filename="http://localhost.com/snapshots/picture.png";
$img = imagecreatefrompng($filename);
$this->_response->setHeader('Content-Type', 'image/png');
imagepng($img,null,9);
imagedestroy($img);
现在实际的图像尺寸是154K所以我通过给出不同的质量水平进行实验,这就是我发现的
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的原因 - 图像尺寸大于实际尺寸.
其次,这是PHP在压缩图像之前压缩图像以提高性能的最佳方式.
基于这些建议,最好在保存时压缩图像一次 - 我挖掘了闪存程序调用的代码以生成快照 -
$video = $this->_getParam('video');
$imgContent = base64_decode($this->_getParam('snapshot'));
file_put_contents("snapshots/" . $video . ".png", $imgContent);
编辑 根据Alvaro的建议,我对代码进行了以下修改,生成了一个非常小的jpg文件
$video = $this->_getParam('video');
$imgContent = base64_decode($this->_getParam('snapshot'));
file_put_contents("snapshots/" . $video . ".png", $imgContent);
$filename="snapshots/".$video.".png";
$img = imagecreatefrompng($filename);
imagejpeg($img,'test.jpg',75);
所以现在这是一个3步骤的过程
这是解决问题的最佳方式吗?
由于 PNG 使用无损数据压缩,因此在 PNG 图像(边缘情况除外)中实现适当压缩的唯一方法是将其保存为调色板(而不是真彩色)并减少颜色数量。您似乎正在处理某种屏幕截图。如果使用有损压缩(即另存为 JPEG),您可能会获得较小的文件大小。无论哪种情况,您都会减小文件大小和图片质量。您还可以尝试 GIF 格式,对于小图形来说,该格式往往较小。
最后但并非最不重要的一点是,您应该压缩图像一次(通常是在上传图像时),而不是每次提供图像时都压缩图像。我想你的代码只是一个快速测试,但我提到以防万一。
回答更新的问题:
我不熟悉 PHP 图像函数,但您可能应该结合使用imagecreatefrompng()和imagejpeg()。另外,请考虑是否需要保留原始 PNG 以供将来参考,或者可以丢弃它。