微信头像生成圆形邀请卡
微信接口获取用户信息,返回的用户头像是132x132的jpeg图片。
用cURL下载微信头像,然后var_dump(getimagesize($avatar));
结果
array(7) {
[0]=>int(132)
[1]=>int(132)
[2]=>int(2)
[3]=>string(24) "width="132" height="132""
["bits"]=>int(8)
["channels"]=>int(3)
["mime"]=>string(10) "image/jpeg"
}
1.先用原生的PHP把头像裁剪成圆形
// 裁剪成圆形图片
public function circleImg($imgpath)
{
// var_dump(getimagesize($imgpath));exit();
// header("content-type:image/png");
$ext = pathinfo($imgpath);
$src_img = null;
switch ($ext['extension']) {
case 'jpeg':
case 'jpg':
$src_img = imagecreatefromjpeg($imgpath);
break;
case 'png':
$src_img = imagecreatefrompng($imgpath);
break;
}
$wh = getimagesize($imgpath);
$w = $wh[0];
$h = $wh[1];
$w = min($w, $h);
$h = $w;
$img = imagecreatetruecolor($w, $h);
imagesavealpha($img, true);
//拾取一个完全透明的颜色,最后一个参数127为全透明
$bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefill($img, 0, 0, $bg);
$r = $w / 2; //圆半径
$y_x = $r; //圆心X坐标
$y_y = $r; //圆心Y坐标
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$rgbColor = imagecolorat($src_img, $x, $y);
if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
imagesetpixel($img, $x, $y, $rgbColor);
}
}
}
imagepng($img, $imgpath);
// imagejpeg($img, $imgpath);
imagedestroy($img);
return true;
}
2.CI框架给背景图加上头像的水印(可选),
注:原本这里想用PHP方法imagecopymerge()来合并两张图片,但是合并后的图片,头像有个白底,如图,估计是jpeg格式的问题,所以选择框架的水印来合并。
public function waterImg($path, $overlay_path, $hor = 0, $pad = 0)
{
$config['image_library'] = 'gd2';
$config['source_image'] = $path;
$config['wm_type'] = 'overlay';
$config['wm_vrt_alignment'] = 'top';
$config['wm_hor_alignment'] = 'left';
$config['wm_hor_offset'] = $hor;
$config['wm_padding'] = $pad;
$config['wm_overlay_path'] = $overlay_path;
$this->load->library('image_lib');
$this->image_lib->initialize($config);
if ($this->image_lib->watermark()) {
//
} else {
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
}
效果图
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: