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

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

一、生成二维码

//获取二维码
  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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353