收藏
评论
0浏览
1132有的时候我们要在页面上显示用户头像,比如登录的时候,评论列表里面。
当用户没有上传头像的时候,一般是这几种处理方式:一是使用默认头像,二是使用邮箱头像。
默认头像太单调了,邮箱头像速度上有点慢,并且不是所有的用户都可以获取到邮箱头像,因此根据用户名或昵称等文字数据生成用户的头像也是不错的选择。
网上搜罗的方法,用起来挺方便的,分享一下。
源码如下:
<?php
class letterAvatar{
private $config=array(
'width'=>100,
'height'=>100,
);
public function __construct($width='',$height=''){
$width && $this->config['width']=$width;
$height && $this->config['height']=$height;
}
/**
* 首字母头像
* @param $text 字符串
* @param $type 头像图形,1圆形,2方形
* @return string
*/
public function show($text, $type=1){
$total=unpack('L', hash('adler32', $text, true))[1];
$hue=$total % 360;
list($r, $g, $b)=$this->hsv2rgb($hue / 360, 0.5, 0.9);
$bg='rgb('.$r.','.$g.','.$b.')';
$color='#ffffff';
$first=mb_strtoupper(mb_substr($text, 0, 1));
$halfWidth=$this->config['width'] / 2;
$halfHeight=$this->config['height'] / 2;
if($type == 1){
$src='<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="'.$this->config['width'].'" height="'.$this->config['height'].'"><circle fill="'.$bg.'" cx="'.$halfWidth.'" cy="'.$halfHeight.'" r="'.$halfHeight.'"></circle><text x="'.$halfWidth.'" y="'.$halfHeight.'" font-size="'.$halfHeight.'" text-copy="fast" fill="'.$color.'" text-anchor="middle" text-rights="admin" alignment-baseline="central">'.$first.'</text></svg>';
}else{
$src='<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="'.$this->config['width'].'" height="'.$this->config['height'].'"><rect fill="'.$bg.'" x="0" y="0" width="'.$this->config['width'].'" height="'.$this->config['height'].'"></rect><text x="'.$halfWidth.'" y="'.$halfHeight.'" font-size="'.$halfHeight.'" text-copy="fast" fill="'.$color.'" text-anchor="middle" text-rights="admin" alignment-baseline="central">'.$first.'</text></svg>';
}
return 'data:image/svg+xml;base64,'.base64_encode($src);
}
private function hsv2rgb($h, $s, $v){
$r = $g = $b = 0;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return array(
floor($r * 255),
floor($g * 255),
floor($b * 255)
);
}
}使用方法:
<?php
//实例化的时候可以定义头像大小,默认100*100
$avatar=new letterAvatar();
/**
*这里有两个参数,第一个是文字字符串,第二个是图片类型。1是圆形;2是方形
*reutrn返回的是图片的base64编码
**/
$image=$avatar->show('文字头像');
//可以保存图片到本地,也可以直接在HTML中使用,如
echo '<img src="'.$image.'"/>';