php 背景图片缩放,PHP按原比率缩小图片并保留透明背景

按原等比率缩小,如果原图是透明的,处理后依旧保留透明/**

* 重置图片文件大小

* @param  string $filePath 文件路径

* @param  int $xmax     最大宽度

* @param  int $ymax     最大高度

* @return boolean       true/false

*/

public function ResetImageFileSize($filePath, $xmax, $ymax)

{

if(filesize($filePath) == 0) return 'error_file';

//$extension = pathinfo($filePath)['extension'];

$extension = explode('/',getimagesize($filePath)['mime'])[1];

$img  = null;

switch ($extension) {

case 'jpg':

case 'jpeg':

$img = imagecreatefromjpeg($filePath);

break;

case 'png':

$img = imagecreatefrompng($filePath);

break;

case 'gif':

$img = imagecreatefromgif($filePath);

break;

case 'webp':

$img = imagecreatefromwebp($filePath);

break;

}

if(is_null($img)) return false;

list($x,$y)  = getimagesize($filePath);

if($x <= $xmax && $y <= $ymax){

return true;

}

/*保留原宽高比率*/

if($x >= $y) {

$newX = ($x > $xmax) ? $xmax : $x;

$newY = $newX * ($y / $x);

}else{

$newY = ($y > $ymax) ? $ymax : $y;

$newX = ($x / $y) * $newY;

}

$img2 = imagecreatetruecolor($newX, $newY);

imageantialias($img2,true);//使用抗锯齿

if($extension == 'png'){

$Color = imagecolorallocatealpha($img2, 0, 0, 0, 127);//设置透明

}else{

$Color = imagecolorallocate($img2,255,255,255);

}

imagecolortransparent($img2,$Color);

imagefill($img2,0,0,$Color);

if(function_exists('imagecopyresampled')){

/*生成图像质量较好,但速度相比较慢*/

imagecopyresampled($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y);

}else{

/*生成图像质量较差,但速度相比较快*/

imagecopyresized($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y);

}

switch ($extension) {

case 'jpg':

case 'jpeg':

imagejpeg($img2,$filePath,100);

break;

case 'png':

imagesavealpha($img2,true);

imagepng($img2,$filePath);

//imagepng($img2,$filePath,9);

break;

case 'gif':

imagegif($img2,$filePath);

break;

default:

imagejpeg($img2,$filePath,100);

break;

}

imagedestroy($img2);

return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值