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

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

小程序端:

.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()
 
    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,
      header: {
        'content-type': 'application/json'
      },
      success: function (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 前端展现形式

  
      
      
      
          
      
  

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 发起请求获取页面小程序码并保存到服务器,返回网络地址。

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; // 返回数据        
}  
?> 

你可能感兴趣的:(微信小程序&PHP 生成小程序码分享图 并保存在手机相册)