今天因为公司小程序要做一个用户海报,需要水印+二维码+头像。 (头像必须要圆的)
因为记得之前好像做过一次,但是实在想不起来,就在网上找了几个试了试, 最后选了一个,原文地址:
https://segmentfault.com/q/1010000007501202
先给大家说一下逻辑。 头像的话,需要先缩略一下。再进行png圆形处理。下面是两个方法的代码:
/**
* $url:是头像路径,$path:是保存路径(../是根目录)
**/
public function resize_img($url,$path='../'){ //先缩略
$imgname = $path.uniqid().'.jpg';
$file = $url;
list($width, $height) = getimagesize($file); //获取原图尺寸
$percent = (140/$width);
//缩放尺寸
$newwidth = $width * $percent;
$newheight = $height * $percent;
$src_im = imagecreatefromjpeg($file);
$dst_im = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($dst_im, $imgname); //输出压缩后的图片
imagedestroy($dst_im);
imagedestroy($src_im);
return $imgname;
}
public function test($url,$path='../'){ //处理圆形
$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;
}
是要分两个步骤的。
经过第二个方法返回的图片就是 下图的 圆形png头像。