100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > php 压缩动态gif php 压缩图片处理png gif背景变黑问题

php 压缩动态gif php 压缩图片处理png gif背景变黑问题

时间:2022-09-20 17:33:47

相关推荐

php 压缩动态gif 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;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。