$newImage = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefrompng($imagePath);
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagepng($newImage, $imagePath, 6);
php7 GD库,有的图片,为啥压缩后变大了 原图100k变300k,300k变700k
完整源码
namespace app\common\model;
use think\Model;
class Attachment extends Model
{
}
$attachment = new Attachment();
$attachment->data(array_filter($params));
$attachment->save();
\think\Hook::listen("upload_after", $attachment);
$this->miniImg($attachment);
public function miniImg($attachment, $maxWidth = 800, $maxHeight = 600, $aspectRatioThreshold = 2) {
if (!stristr($attachment->mimetype, 'image')) {
return;
}
$imagePath = ltrim($attachment->url, '/');
if (!file_exists($imagePath)) {
return;
}
$fileSize = filesize($imagePath);
if ($fileSize < 300 * 1024) {
return; // 如果文件小于300KB,则不处理
}
list($width, $height, $type) = getimagesize($imagePath);
$newWidth = $width;![]
$newHeight = $height;
// 如果宽度或高度超过最大值,则进行特殊处理
if ($width > $maxWidth || $height > $maxHeight) {
$ratio = max($width / $maxWidth, $height / $maxHeight);
$newWidth = ceil($width / $ratio);
$newHeight = ceil($height / $ratio);
if ($width / $height > $aspectRatioThreshold) {
$newHeight = ceil($newWidth / $aspectRatioThreshold);
} elseif ($height / $width > $aspectRatioThreshold) {
$newWidth = ceil($newHeight * $aspectRatioThreshold);
}
}
$newImage = imagecreatetruecolor($newWidth, $newHeight);
switch ($type) {
case IMAGETYPE_JPEG:
$source = imagecreatefromjpeg($imagePath);
break;
case IMAGETYPE_PNG:
$source = imagecreatefrompng($imagePath);
break;
case IMAGETYPE_GIF:
$source = imagecreatefromgif($imagePath);
break;
case IMAGETYPE_WEBP:
$source = imagecreatefromwebp($imagePath);
break;
default:
return; // 不支持的图片类型
}
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
switch ($type) {
case IMAGETYPE_JPEG:
imagejpeg($newImage, $imagePath, 60);
break;
case IMAGETYPE_PNG:
imagepng($newImage, $imagePath, 6);
break;
case IMAGETYPE_GIF:
imagegif($newImage, $imagePath);
break;
case IMAGETYPE_WEBP:
imagewebp($newImage, $imagePath, 60);
break;
}
imagedestroy($source);
imagedestroy($newImage);
}
大部分图片可以压缩
PNG图片不要进行图片质量压缩,仅做长宽大小的处理,如果长宽缩小后png感觉还是大,可以转换成WEBP格式,WEBP的压缩率很高