PHP:如何压缩图像而不损失可见质量(自动)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19696187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How to compress images without losing visible quality (automatically)?
提问by Mr. B.
I'm wondering how to figure out the best compress rate (small filesize + no quality loss) automatically.
我想知道如何自动找出最佳压缩率(小文件+无质量损失)。
At the moment I'm using imagejpeg()with $quality = 85
for each .jpg
.
目前我正在使用imagejpeg()和$quality = 85
for each .jpg
。
PageSpeed (Chrome Plugin) suggests, to lower the quality of a few images to save some kb. The percentage of reduction is different.
PageSpeed(Chrome 插件)建议,降低一些图像的质量以节省一些 kb。减少的比例不同。
I'd like to write a cronjob that crawls a specific directory and optimizes every image.
我想编写一个 cronjob 来抓取特定目录并优化每个图像。
How does PageSpeed or TinyPNGfigure out the best optimized quality and is this possible with PHP or another serverside-language?
PageSpeed 或TinyPNG如何找出最佳优化质量,这是否可以使用 PHP 或其他服务器端语言?
回答by Kornel
TinyPNG uses pngquant.
TinyPNG使用pngquant。
Pngquant has option to set desired quality, similar to JPEG. You can run something like:
Pngquant 可以选择设置所需的质量,类似于 JPEG。您可以运行以下内容:
<?php system('pngquant --quality=85 image.png'); ?>
Pngquant website has example code showing how to use pngquant from PHP.
pngquant 网站有示例代码,展示了如何使用 PHP 中的 pngquant。
For JPEG you can apply losslessjpegcrush.
对于 JPEG,您可以应用无损jpegcrush。
JpegMini(commercial) and jpeg-archive(free) are lossyand can can automatically find a minimal good quality for a JPEG.
JpegMini(商业)和jpeg-archive(免费)是有损的,可以自动找到 JPEG 的最低质量。
In PHP you can roughly estimate how much JPEG was compressed by observing how much file size changes after re-compression. File size of JPEG recompressed at same or higher quality will not change much (but will lose visual quality).
在 PHP 中,您可以通过观察重新压缩后文件大小的变化来粗略估计 JPEG 被压缩了多少。以相同或更高质量重新压缩的 JPEG 文件大小不会有太大变化(但会损失视觉质量)。
If you recompress JPEG and see file size halved, then keep the recompressed version. If you see only 10-20% drop in file size, then keep the original.
如果您重新压缩 JPEG 并看到文件大小减半,则保留重新压缩的版本。如果您看到文件大小仅减少 10-20%,请保留原始文件。
If you're compressing yourself, use MozJPEG(here's an online version).