PHP 小程序码中心图片更换LOGO

    /**
     * 将小程序码与LOGO合并
     */
    public function imageMerge($bgimg, $logoimg)
    {
        $path = ROOT_PATH.'public/uploads/';

        //原小程序码 背景图
        $bgimg = $path.$bgimg;
        //LOGO 需要插入到背景图的图片url
        $logoimg = $path.$logoimg;

        if ($bgimg) {
            //这是合成后的图片保存的路径
            $upload_dir = "public/uploads/wechat/";
            if (is_file($bgimg)) {
                //创建画布
                $bg = imagecreatefromstring(file_get_contents($bgimg));
                $logo = $this->yuan_img($logoimg);

                //将$logoimg插入到$bgimg里
                imagecopyresampled($bg, $logo, 166, 166, 0, 0, 268, 268, imagesx($logo), imagesy($logo));


                //生成图片
                $img_name = md5($bgimg.$logoimg.time().rand(100000,999999)).'.png';
                imagepng($bg, ROOT_PATH.$upload_dir.$img_name);
                //生成图片名字
                $twocode = 'wechat/'.$img_name;
            }
            //删除原小程序码
            unlink($bgimg);
            return $twocode;//返回结果图片url
        } else {
            return false;
        }
    }

    /**
     * 图片转换为圆形
     */
    public function yuan_img($imgpath) {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgpath);
                break;
            case 'gif':
                $src_img = imagecreatefromgif($imgpath);
                break;
        }
        $wh  = getimagesize($imgpath);
        $w   = $wh[0];
        $h   = $wh[1];
        $min = min($w, $h);
        $img = imagecreatetruecolor($min, $min);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $min / 2; //圆半径
        for ($x = $w/2 - $r; $x < $w; $x++) {
            for ($y = $h/2 - $r; $y < $h; $y++) {

                $rgbColor = imagecolorat($src_img, $x, $y);

                $y_x = $w/2; //圆心X坐标
                $y_y = $h/2; //圆心Y坐标
                if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))){
                    imagesetpixel($img, $x - ($w/2 - $r), $y - ($h/2 - $r), $rgbColor);
                }
            }
        }
        return $img;
    }

 

posted @ 2020-10-20 10:37  暮雨浅忆  阅读(460)  评论(0编辑  收藏  举报