php 无损压缩图片
基于composer
库中代码仅仅可以支持长宽比原图小的压缩参数,如需等于或者等于原图大小的需要调整代码;
实测压缩效果略低于tinypng ,但二次压缩会大小不变;
-
该库方法有问题,结果显示,用tinypng压缩后的图片,用该库方法处理结果,图片会变大,效果相反!
-
调整代码如下:
/**
* @param $picPath //待缩放的图片路径
* @param $width //缩放的宽度,目标宽度;
* @param $height //缩放的高度,目标高度;
* @param bool $rotate //图片是否旋转
* @return bool|string
*/
public function pictureThumb($picPath,$width = '',$height = '',$rotate=false)//图片缩放
{
$imageInfo = $this->makeInternalImg($picPath);
$picWidth = $imageInfo['imgInfo'][0];
$picHeight = $imageInfo['imgInfo'][1];
// added zb 如果未设置大小,抓取自身图片大小;
if(!$width) $width = $picWidth;
if(!$height) $height = $picHeight;
if(!file_exists($picPath)) return false;
$setRes = $this->setThumbImgPath($picPath,$width,$height);
if(!is_null($setRes)) return $this->thumbOutPath;
//根据参数$width和height值,换算出等比例缩放的宽度和高度
$resizeWidthTag=$resizeHeightTag=false;
$widthRatio=$heightRatio=0;
$ratio = 0;//压缩比例
if($width ){//&& $picWidth>$width chged zb
$widthRatio = $width/$picWidth;
$resizeWidthTag = true;
}
if($height ){//&& $picHeight>$height chged zb
$heightRatio = $height/$picHeight;
$resizeHeightTag = true;
}
if($resizeWidthTag && $resizeHeightTag){
if($widthRatio<$heightRatio)
$ratio = $widthRatio;
else
$ratio = $heightRatio;
}
if($resizeWidthTag && !$resizeHeightTag)
$ratio = $widthRatio;
if($resizeHeightTag && !$resizeWidthTag)
$ratio = $heightRatio;
$newWidth = $picWidth * $ratio;
$newHeight = $picHeight * $ratio;
//在内存中建立一个宽$width,高$height的真色彩画布
$imageThumb=imagecreatetruecolor($newWidth,$newHeight);
//将原图复制到新建的真色彩的画布上,并且按一定比例压缩
imagecopyresampled($imageThumb,$imageInfo['src_img'],0,0,0,0,$newWidth,$newHeight,$imageInfo['imgInfo'][0],$imageInfo['imgInfo'][1]);
imagedestroy($imageInfo['src_img']);
if($rotate){
$resource=$this->imageRotate($imageThumb,$degrees=90,$bgd_color=0);//旋转图片
if(!$resource){
return false;
}
$imageInfo['src_img']=$resource;
}else{
$imageInfo['src_img']=$imageThumb;
}
$this->destroyImg($imageInfo,$imageThumb);
return $this->thumbOutPath;
}
相信坚持的力量,日复一日的习惯.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2019-07-26 微信小程序企业付款到个人
2019-07-26 秒 转化为 时:分:秒 ------- 类似倒计时
2019-07-26 navigationBarTitleText