微信介面獲取使用者資訊,返回的使用者頭像是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 協議》,轉載必須註明作者和本文連結