微信头像生成圆形邀请卡

微信接口获取用户信息,返回的用户头像是132x132的jpeg图片。
file
用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()来合并两张图片,但是合并后的图片,头像有个白底,如图file,估计是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();
    }

效果图
file

php
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 2

可以,很强

5年前 评论

咋么操作的,我的 合成的头像怎么是黑白色了

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!