欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序&PHP 生成小程序码分享图 并保存在手机相册

程序员文章站 2024-02-10 14:34:52
...

注意:小程序端如果想保存成图片,需要用画布,但是如果想把图片放在画布上,真机上需要先把图片保存到本地。使用缓存文件!!!!!

小程序端:

  .js

import util from '../../../utils/util'
var image = require('../../../utils/util.js'); 
const app = getApp(); 
Page({
  data: {
    allthing: app.globalData,
  },
  onLoad: function (options) {
    var that = this;
    var imageSize = image.image()
    console.log(imageSize)
    that.setData({
      imageWidth: imageSize.imageWidth,
      imageHeight: imageSize.imageHeight,
      chaWidth: imageSize.chaWidth,
      chaHeight: imageSize.chaHeight,
    })
    that.getAvatarUrl(that.data.allthing.userInfo.avatarUrl)
    that.getSpecialM()
    that.getBackground()
    that.getTouground()
    wx.showToast({
      title: '正在生成图片',
      icon: 'loading',
      duration: 10000,
    })
    setTimeout(function () {           //延迟执行,避免请求文件无效
      console.log("----Countdown----")
      that.createImg()
      wx.hideToast()
    }, 1000)
  },
  /**
   * 获取特定页面的小程序码
   */
  getSpecialM:function(){
    var that = this
    //请求获取小程序码
    wx.request({
      method: 'GET',
      url: 'https://www.a******_code.php?sid=' + that.data.userInfo.subject_id,//小程序有关token的api接口需要写在后台服务器端
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        wx.downloadFile({
          url: res.data.data.url,
          success: function (res) {
            that.setData({
              icon4: res.tempFilePath,
            })
          },
          fail: function () {
            console.log('fail')
          }
        })
      }
  })
},
  /**
   * 获取头像
   */
  getAvatarUrl: function (avatarUrl){
    var that = this
    //保存头像
    wx.downloadFile({
      url:avatarUrl,
      success: function (res) {
        that.setData({
          exam: res.tempFilePath,
        })
      },
      fail: function () {
        console.log('fail')
      }
    })
  },
  /**
   * 获取背景
   */
  getBackground: function () {
    var that = this
    wx.downloadFile({
      url: 'https://app.c***answer/2.png',
      success: function (res) {
        that.setData({
          share: res.tempFilePath,
        })
      },
      fail: function () {
        console.log('fail')
      }
    })
  },
  /**
   * 获取头像框
   */
  getTouground: function () {
    var that = this
    wx.downloadFile({
      url: 'https://app.ci1*******er/phot.png',
      success: function (res) {
        that.setData({
          phot: res.tempFilePath,
        })
      },
      fail: function () {
        console.log('fail')
      }
    })
  },
  /**
   * 生成画布
   */
  createImg:function(){
    var that  = this 
    var ctx = wx.createCanvasContext('myCanvas');
    ctx.setFillStyle('White')
    ctx.fillRect(0, 0, 300, 400)
    ctx.drawImage(that.data.icon4, 115 + that.data.chaWidth / 2, 153 + that.data.chaHeight / 2, 92, 92)
    ctx.drawImage(that.data.share, 0, 0, that.data.imageWidth, that.data.imageHeight)
    ctx.drawImage(that.data.exam, 138 + that.data.chaWidth / 2, 10 , 50, 50)
    ctx.drawImage(that.data.phot, 138 + that.data.chaWidth / 2, 10, 50, 50)
    ctx.draw();
  },
  savePic: function () {       //保存图片触发事件
    var that = this
    wx.canvasToTempFilePath({
      width: that.data.imageWidth,
      height: that.data.imageHeight,
      canvasId: 'myCanvas',
      success: function (res) {
        util.savePicToAlbum(res.tempFilePath)
      }
    })
    setTimeout(function () {
      console.log("----Countdown----")
      wx.redirectTo({
        url: '/pages/my/my/my',
      })
    }, 1000)
   
  }
})

.wxml

<view>
    <canvas style="width:{{imageWidth}}px;height:{{imageHeight}}px" canvas-id="myCanvas" class='canvas'></canvas>
    <!--测试按钮-->
    <view class="edit-footer">
        <button class="button-done" type="primary" bindtap="savePic">保存图片</button>
    </view>
</view>


util.js

function savePicToAlbum(tempFilePath) {
  let that = this;
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showToast({
                  title: '保存成功'
                });
              },
              fail(res) {
                console.log(res);
              }
            })
          },
          fail() {
            // 用户拒绝授权,打开设置页面
            wx.openSetting({
              success: function (data) {
                console.log("openSetting: success");
              },
              fail: function (data) {
                console.log("openSetting: fail");
              }
            });
          }
        })
      } else {
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
            });
          },
          fail(res) {
            console.log(res);
          }
        })
      }
    },
    fail(res) {
      console.log(res);
    }
  })
}
function image() {
  var imageSize = {};
  var originalScale = 0.2;//图片高宽比  
  //获取屏幕宽高  
  wx.getSystemInfo({
    success: function (res) {
      var windowWidth = res.windowWidth;
      var windowHeight = res.windowHeight;
      var windowscale = windowHeight / windowWidth;//屏幕高宽比  
      console.log('windowWidth: ' + windowWidth)
      console.log('windowHeight: ' + windowHeight)
      if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比  
        //图片缩放后的宽为屏幕宽  
        imageSize.imageWidth = windowWidth;
        imageSize.imageHeight = (windowWidth * 400) / 320;
        imageSize.chaWidth = windowWidth-320; 
        imageSize.chaHeight = (windowWidth * 400) / 320 - 400; 
      } else {//图片高宽比大于屏幕高宽比  
        //图片缩放后的高为屏幕高  
        imageSize.imageHeight = windowHeight;
        imageSize.imageWidth = (windowHeight * 320) / 400;
        imageSize.chaWidth = windowWidth - 320;
        imageSize.chaHeight = (windowWidth * 400) / 320 - 400; 
      }

    }
  })
  console.log('缩放后的宽: ' + imageSize.imageWidth)
  console.log('缩放后的高: ' + imageSize.imageHeight)
  return imageSize;
}
module.exports = {
  formatTime: formatTime,
  savePicToAlbum: savePicToAlbum,
  image:image
}

服务器端

create_wxa_code.php

<?php
include_once('/opt*****/function.php');
include_once('/opt*****n/config.php');//$appid和$secret保存其中
$sid = addslashes($_GET['sid']);
//token存在缓存中
$access_token=M::Get('q*******en_'.$appid);
if(!$access_token){
        $url_access_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $json_access_token = sendCmd($url_access_token,array());
        //access_token加缓存
        $arr_access_token = json_decode($json_access_token,true);
        $access_token = $arr_access_token['access_token'];
        M::Set('q******ken_'.$appid,$access_token,3600);
}
if(!empty($access_token)) {
	$url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;    
 	$data = '{"path": "/pages/a*****/index?id='.$sid.'", "width":430}';
     	$result = sendCmd($url,$data);

	$dir = "/opt/c******wxaapp/";
	$path = $dir.date("Y/m/d/")."/".rand(1,50)."/";
	create_dirs($path,0777);
	$file_name = time().".png";
		
	file_put_contents($path.$file_name,$result);
	$url = 'https://www.q****om/'.str_replace('/op*****baby/','',$path.$file_name);

	$arr = array('ret'=>1,
		'msg'=>'success',
		'data'=>array('url'=>$url),   //返回保存在服务器中小程序码的地址
		);
} else {
	$arr = array('ret'=>0,'msg'=>'ACCESS TOKEN为空!');
}
	echo json_encode($arr);


/**
 * 发起请求
 * @param  string $url  请求地址
 * @param  string $data 请求数据包
 * @return   string      请求返回数据
 */
function sendCmd($url,$data)
{
    $curl = curl_init(); // 启动一个CURL会话      
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址                  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测    
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在      
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交     
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转      
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer      
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求      
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包      
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循     
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容      
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 
           
    $tmpInfo = curl_exec($curl); // 执行操作      
    if (curl_errno($curl)) {      
       echo 'Errno'.curl_error($curl);      
    }      
    curl_close($curl); // 关键CURL会话      
    return $tmpInfo; // 返回数据      
}
?>