问题描述
最近在项目中,需要后端进行图片合并。由于头像是圆形、png格式,合并到背景图片后会出现四个黑角或白边的情况。
解决方法
为添加透明通道信息
代码如下:
图片切成圆形
path 为存储路径
function cutCirle($url){
$path = public_path('/uploads/public/code_'.time().'.png');
$w = 110; $h=110; // original size
$original_path= $url;
$dest_path = $path.uniqid().'.png';
$src = imagecreatefromstring(file_get_contents($original_path));
$newpic = imagecreatetruecolor($w,$h);
imagealphablending($newpic,false);
$transparent = imagecolorallocatealpha($newpic, 0, 0, 0, 127);
$r=$w/2;
for($x=0;$x<$w;$x++)
for($y=0;$y<$h;$y++){
$c = imagecolorat($src,$x,$y);
$_x = $x - $w/2;
$_y = $y - $h/2;
if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
imagesetpixel($newpic,$x,$y,$c);
}else{
imagesetpixel($newpic,$x,$y,$transparent);
}
}
imagesavealpha($newpic, true);
imagepng($newpic, $dest_path);
imagedestroy($newpic);
imagedestroy($src);
// unlink($url);
return $dest_path;
}
图片合并及添加透明通道信息
/**
$dst是背景图片
*/
$getHead = $this->headImg(cutCirle);
list($head_w,$head_h) = getimagesize($getHead['resize']); //获取长宽
$headImg = imagecreatefrompng($getHead['resize']);
$dst_im = imagecreatetruecolor($head_w, $head_h); //创建画报
$bg = imagecolorallocatealpha($dst_im,0,0,0,127); //alpha色
imagealphablending($dst_im,false);
imagefill($dst_im,0,0,$bg);//4.填充透明色
imagecopyresized($dst_im, $headImg, 0, 0, 0, 0, $head_w, $head_h, $head_w, $head_h); //头像与画报合并
//用户头像
imagecopyresized($dst,$dst_im,72,30,0,0,imagesx($dst_im),imagesy($dst_im),imagesx($dst_im),imagesy($dst_im));
imagesavealpha($dst_im,true);//重要!!与背景图片合并后,需要保存alpha