如何使用PHP实现图片的无损压缩和优化

admin2年前javascript1242

<?php
function compressImage($source, $destination, $maxWidth, $maxHeight, $quality) {
 $info = getimagesize($source);
 $width = $info[0];
 $height = $info[1];
 
 // 计算缩放比例
 $scale = min($maxWidth/$width, $maxHeight/$height);
 
 // 计算缩放后的宽度和高度
 $newWidth = $width * $scale;
 $newHeight = $height * $scale;
 
 // 创建缩略图
 $thumb = imagecreatetruecolor($newWidth, $newHeight);
 
 // 根据原图类型进行相应的处理
 if ($info['mime'] == 'image/jpeg') {
     $sourceImage = imagecreatefromjpeg($source);
 } elseif ($info['mime'] == 'image/png') {
     $sourceImage = imagecreatefrompng($source);
 } elseif ($info['mime'] == 'image/gif') {
     $sourceImage = imagecreatefromgif($source);
 } else {
     return false;
 }
 
 // 将原图复制到缩略图中
 imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
 
 // 保存缩略图
 if ($info['mime'] == 'image/jpeg') {
     imagejpeg($thumb, $destination, $quality);
 } elseif ($info['mime'] == 'image/png') {
     imagepng($thumb, $destination, 9);
 } elseif ($info['mime'] == 'image/gif') {
     imagegif($thumb, $destination);
 }
 
 return true;
}

// 使用示例
$sourceImage = 'source.jpg';
$destinationImage = 'compressed.jpg';
$maxWidth = 800;
$maxHeight = 600;
$quality = 75;
compressImage($sourceImage, $destinationImage, $maxWidth, $maxHeight, $quality);

相关文章

vue项目没有安装chokidar

很久之前完成的项目,从git上面拉取下来以后使用npm i指令安装好依赖包后,使用npm run serve指令运行项目却出现了报错。在这里插入图片描述明明所有的依赖包都是自动安装的,并没有额外安装,...

laydate使用

laydate.render({         elem: '#dateinput',&n...

rem与px换算的计算方式

rem与px换算的计算方式

前言这段时间的小项目中算是真正意义上使用了rem来进行移动端的页面布局,项目结束了我反思了一下之前的对于rem的使用...原来我以前对rem用法完全是在搞笑啊!!结合这次这个小项目,我觉得我也有必要对...

vue-element-admin文档

https://panjiachen.gitee.io/vue-element-admin-site/zh/...

对promise、resolve和reject的简单理解

        Promise构造函数接受一个函数作为参数,其中该参数又接受两个函数作为它自身的参数,分别是resolve和rej...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。