PHP:如何压缩图像而不损失可见质量(自动)?

2022-01-03 00:00:00 cron image compression php server-side

我想知道如何自动确定最佳压缩率(小文件+无质量损失).

I'm wondering how to figure out the best compress rate (small filesize + no quality loss) automatically.

目前我正在使用 imagejpeg() 和 $quality = 85 对于每个 <代码>.jpg.

At the moment I'm using imagejpeg() with $quality = 85 for each .jpg.

PageSpeed(Chrome 插件)建议降低一些图像的质量以节省一些 kb.减少的百分比不同.

PageSpeed (Chrome Plugin) suggests, to lower the quality of a few images to save some kb. The percentage of reduction is different.

我想编写一个 cronjob 来抓取特定目录并优化每个图像.

I'd like to write a cronjob that crawls a specific directory and optimizes every image.

PageSpeed 或 TinyPNG 如何确定最佳优化质量,这是否可以使用 PHP 或其他服务器端语言?

How does PageSpeed or TinyPNG figure out the best optimized quality and is this possible with PHP or another serverside-language?

推荐答案

TinyPNG 使用 pngquant.

TinyPNG uses pngquant.

Pngquant 可以选择设置所需的质量,类似于 JPEG.您可以运行以下内容:

Pngquant has option to set desired quality, similar to JPEG. You can run something like:

<?php system('pngquant --quality=85 image.png'); ?>

Pngquant 网站上的示例代码展示了如何使用 PHP 中的 pngquant.

对于 JPEG,您可以应用 lossless jpegcrush.

For JPEG you can apply lossless jpegcrush.

JpegMini(商业)和 jpeg-archive(免费)有损,可以自动为 JPEG 找到最低质量的质量.

JpegMini (commercial) and jpeg-archive (free) are lossy and can can automatically find a minimal good quality for a JPEG.

在 PHP 中,您可以通过观察重新压缩后文件大小的变化来粗略估计 JPEG 被压缩了多少.以相同或更高质量重新压缩的 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).

如果您重新压缩 JPEG 并看到文件大小减半,则保留重新压缩的版本.如果您看到文件大小仅减少 10-20%,请保留原始文件.

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.

如果您要压缩自己,请使用 MozJPEG(这是一个 网络版).

If you're compressing yourself, use MozJPEG (here's an online version).

相关文章