php压缩png图片错误,php 压缩图片处理png、gif背景变黑问题

/**

* 压缩图片

* @param $imgsrc 图片路径

* @param string $imgdst 压缩后保存路径

* @param int $quality 压缩图片的质量

* @return string

*/

public function compressedImage($imgsrc, $imgdst="",$quality=75) {

//绝对路径 或者相对路径去掉前面的/

//if (!is_file($imgsrc))$imgsrc= __DIR__ . '/'.$imgsrc;

list($width, $height, $type) = getimagesize($imgsrc);

if ($imgdst==""){

$position1 = strrpos($imgsrc,'/');

$path1 = substr($imgsrc,0,$position1);

$name1=substr($imgsrc,$position1+1);

$imgdst=$path1."/thumb/".$name1;

// $arrtmp=explode("/",$imgsrc);

// array_splice($arrtmp, count($arrtmp)-1, 0, array("thumb"));

// $imgdst=implode("/",$arrtmp);

}

if (is_file($imgdst)){return $imgdst;}

$new_width = $width;//压缩后的图片宽

$new_height = $height;//压缩后的图片高

if($width >= 620){

$per = 620 / $width;//计算比例

$new_width = $width * $per;

$new_height = $height * $per;

}

//print_r($type);exit();

//创建文件交

$position = strrpos($imgdst,'/');

$path = substr($imgdst,0,$position);

if(!file_exists($path)){mkdir($path,0777,true);}

switch ($type) {

case 1:

$giftype = check_gifcartoon($imgsrc);

if ($giftype) {

//header('Content-Type:image/gif');

$image_wp = imagecreatetruecolor($new_width, $new_height);

/* --- 用以处理缩放gif和png图透明背景变黑色问题 开始 --- */

$color = imagecolorallocate($image_wp,255,255,255);

imagecolortransparent($image_wp,$color);

imagefill($image_wp,0,0,$color);

/* --- 用以处理缩放gif和png图透明背景变黑色问题 结束 --- */

$image = imagecreatefromgif($imgsrc);

imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

//90代表的是质量、压缩图片容量大小

imagejpeg($image_wp, $imgdst, $quality);

imagedestroy($image_wp);

imagedestroy($image);

}

break;

case 2:

//header('Content-Type:image/jpeg');

$image_wp = imagecreatetruecolor($new_width, $new_height);

$image = imagecreatefromjpeg($imgsrc);

imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

//90代表的是质量、压缩图片容量大小

imagejpeg($image_wp, $imgdst, $quality);

imagedestroy($image_wp);

imagedestroy($image);

break;

case 3:

//header('Content-Type:image/png');

$image_wp = imagecreatetruecolor($new_width, $new_height);

/* --- 用以处理缩放gif和png图透明背景变黑色问题 开始 --- */

$color = imagecolorallocate($image_wp,255,255,255);

imagecolortransparent($image_wp,$color);

imagefill($image_wp,0,0,$color);

/* --- 用以处理缩放gif和png图透明背景变黑色问题 结束 --- */

$image = imagecreatefrompng($imgsrc);

imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

//90代表的是质量、压缩图片容量大小

imagejpeg($image_wp, $imgdst, $quality);

imagedestroy($image_wp);

imagedestroy($image);

break;

}

return $imgdst;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值