PHP 压缩图片

WechatIMG6.jpeg

在使用gd库压缩图片时,png透明底的图片没办法处理,而且会导致图片损坏,所以建议使用其他方式来对png的图片进行处理,例如pngquant。它被专门用来压缩PNG图像,同时最大限度地降低质量损失。

安装pngquant

  • ubuntu 安装
1
$ apt install pngquant
  • mac 安装
1
$ brew install pngquant
  • 查看版本
1
$ pngquant --version

安装php-pngquant

  • composert 安装 php-pngquant
1
$ composer install ourcodeworld/php-pngquant

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
require_once 'vendor/autoload.php';
use ourcodeworld\PNGQuant\PNGQuant;
/**
* 压缩图片
* @param string $source_url 原图片路径
* @param string $destination_url 压缩图片路径
* @param string $quality 压缩质量,取值范围为0-100,默认值为75。为0时,表示使用默认的压缩质量。为100时,表示不进行压缩。
* @return string destination_url
*/
function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source_url);
imagejpeg($image, $destination_url, $quality);
} elseif ($info['mime'] == 'image/png') {
vendor('PNGQuant.PNGQuant');
$pngquant = new \PNGQuant();
$exit_code = $pngquant->setImage($source_url)
->setOutputImage($destination_url)
->overwriteExistingFile()
->setQuality(50,80)
->execute();
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source_url);
imagejpeg($image, $destination_url, $quality);
}
return $destination_url;
}
-------------本文结束感谢您的阅读-------------
0%