美文网首页
生成二维码并合成到海报图

生成二维码并合成到海报图

作者: 洗耳恭听_kai | 来源:发表于2020-10-11 17:11 被阅读0次

引言: 需要做分销系统,分享相关的海报图,海报图中带有特定的二维码。扫码功能分开下一篇总结

一、生成二维码

//获取二维码
  getqrcode:function(){
    var that = this
    app.reqPost("share", "getcode", {
      PHPSESSID: wx.getStorageSync('PHPSESSID'),  //这里是用来后台查找对应的用户信息的,可以根据自己的参数来
      appid:config.AppID,
      appsecret:config.AppSecret
    }, function (res) {
      console.log(res)
      wx.hideLoading();
      that.setData({ 
        image: config.image_url + res.data.img
      });
    })
  },
public function getcode(){
        //配置APPID、APPSECRET
        $sessionid = $_POST['PHPSESSID'];
        $APPID = $_POST['appid'];
        $APPSECRET =  empty($_REQUEST['appSecret'])?"d3223726652207xxxxxx":$_REQUEST['appSecret'];
        $userinfo = Db::name('users')->where('sessionid',$sessionid)->find();
        $uid = $userinfo['id'];
        //判断是否已有二维码
        if(!empty($userinfo['share_qrcode'])){
            return json(['code'=>'1000','msg'=>'成功','img'=>$userinfo['share_qrcode']]);
        }
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

        $json = $this->httpRequest( $access_token );
        $json = json_decode($json,true);
        $ACCESS_TOKEN = $json["access_token"];

        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        //这里的path的路径规则需要在小程序微信平台去配置,具体在下一篇文章会说到
        $param = json_encode(array("path"=>"https://rrt.jcyhl.com/share/index?shareid=$uid","width"=> 150));

        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //生成二维码
        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );

        //处理base64图片,这里获取到的是二进制流,需要转换为jpg类型存储到文件夹和数据库
        if (strstr($base64_image,",")){
            $image = explode(',',$base64_image);
            $image = $image[1];
        }

        //存储到文件夹
        $destination = $_SERVER['DOCUMENT_ROOT'].'/static/upload/images/share_qrcode/';
        $filename = date("YmdHis",time()).'-'.substr(md5($image),0,10).'.png';
        $filename_img = $destination.$filename;
        $r = file_put_contents($filename_img, base64_decode($image));
        if (!$r) {
            return json(['data'=>null,"code"=>1,"msg"=>"图片生成失败"]);
        }

        //存储到数据库
        $img_url = '/upload/images/share_qrcode/'.$filename;
        $update = [
            'share_qrcode' => $img_url
        ];
        Db::name('users')->where('id',$uid)->update($update);

        return json(['code'=>'1000','msg'=>'成功','img'=>$img_url]);

    }

二、合并到海报图

首先需要准备一张做好的海报图

获取界面宽高

data: {
    imgurl: config.image_url,
    windowWidth:'',
    windowHeight:'',
    bgimg: config.image_url + '/upload/wxmini/' + 'wx_share.jpg',
    image: '',
    uid:'',
    username:'',
    reportHeight: '',
    temporarycodeUrl:'',
    maskshow: false,
  },
onLoad: function (options) {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        });
      }
    });
    this.init()
  },

合并到画布

canvasCode() {
    wx.showLoading({
        title: '生成二维码中',
        mask: true
      })
      let that = this
      //let modal = wx.getSystemInfoSync();          // 获取手机信号以iphone 6s为例
      let width = that.data.windowWidth                // 获取手机屏幕的宽度
      // 根据手机屏幕比例计算出画布的高度
      let height = that.data.windowHeight - 50                
      let scale = that.data.windowWidth / 375
      that.setData({
        maskshow: true,            // 显示装载海报的容器
        reportHeight: height       // 设置二维码海报的高度
      })
      const ctx = wx.createCanvasContext('codereport', this)  // 创建画布
      // 生成海报图
      wx.getImageInfo({
        src: that.data.bgimg,                              // 海报图的网络路径
        success: function (res) {
          let path = res.path                              // 获取海报图的本地路径
          ctx.drawImage(path, 0, 0, width-20, height-20)         // 将海报绘制进画布 top为0,left为0,设置海报的宽高
          let codewidth = that.data.windowWidth * 0.2          // 设置二维码宽度
          let codeheight = codewidth                         // 设置二维码高度 
          let top = height * 0.52                            // 设置二维码在海报里的向上偏移量
          let left = that.data.windowWidth * 0.38              // 设置二维码在海报里的向左偏移量
          setTimeout(function () {
            // 二维码图
            wx.getImageInfo({
              src: that.data.image,                      // 二维码的网络路径
              success: function (res) {
                console.log(res)                    
                let code = res.path                        // 获取二维码的本地路径
                ctx.drawImage(code, left, top, codewidth, codeheight)    // 将二维码绘制进画布 top为0,left为0,设置海报的宽高    
                ctx.draw(that)                             // 把绘制好的图形画进canvas
                wx.hideLoading()
                wx.canvasToTempFilePath({                   // 把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径                                  
                  canvasId: 'codereport',
                  success: function (res) {
                    let tempFilePath = res.tempFilePath;
                    that.setData({
                      temporarycodeUrl: tempFilePath   //下载保存的时候需要
                    })
                    console.log(that.data.temporarycodeUrl)
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
              }
            })
          }, 0)
        }
      })
  },
<view class="haibao" style="width:100%;">
  <canvas class="canvas" canvas-id="codereport"  style="width:100%;height:{{ reportHeight-50 }}px;margin-left:10px;margin-top:10px;" bindtap="closeImg"></canvas>
  <view class='c' bindtap='saveImg'>保存海报</view>
</view>

根据自己的需求调整二维码的位置

.wxss

.a{
  width: 100%;
  position: relative;
  margin-top: 20px;
}
.a image{
  height: 600px;
  margin-left: 30px;
}

.b image{
  width: 79px;
  height: 76px;
  position:absolute;
  bottom: 271px;
  right:80px;
}

.c {
  font-size:30rpx;color:rgb(38, 109, 79);width:600rpx;height:80rpx;border-radius:50rpx;text-align:center;line-height:80rpx;margin:38rpx auto;
  background-color: rgb(206, 221, 207);
}

.json

{
  "navigationBarTitleText": "推广名片",
  "enablePullDownRefresh": true,
  "backgroundTextStyle": "dark"
}

三、效果

image.png

相关文章

网友评论

      本文标题:生成二维码并合成到海报图

      本文链接:https://www.haomeiwen.com/subject/oadlpktx.html