注意:小程序端如果想保存成圖片或辖,需要用畫布瘾英,但是如果想把圖片放在畫布上,真機(jī)上需要先把圖片保存到本地颂暇。
解決方法:使用緩存文件H鼻础!s凹堋0曷浮榆骚!
小程序端:
.js 小程序前端數(shù)據(jù)處理
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,
})
//延遲執(zhí)行,避免請(qǐng)求文件無效
setTimeout(function () {
console.log("----Countdown----")
//生成圖片
that.createImg()
wx.hideToast()
}, 1000)
},
/**
* 獲取特定頁面的小程序碼
*/
getSpecialM:function(){
var that = this
//請(qǐng)求獲取小程序碼
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();
},
//保存圖片觸發(fā)事件
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 前端展現(xiàn)形式
<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() {
// 用戶拒絕授權(quán),打開設(shè)置頁面
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
}
服務(wù)器端
create_wxa_code.php 發(fā)起請(qǐng)求獲取頁面小程序碼并保存到服務(wù)器妓肢,返回網(wǎng)絡(luò)地址捌省。
<?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), //返回保存在服務(wù)器中小程序碼的地址
);
} else {
$arr = array('ret'=>0,'msg'=>'ACCESS TOKEN為空!');
}
echo json_encode($arr);
/**
* 發(fā)起請(qǐng)求
* @param string $url 請(qǐng)求地址
* @param string $data 請(qǐng)求數(shù)據(jù)包
* @return string 請(qǐng)求返回?cái)?shù)據(jù)
*/
function sendCmd($url,$data)
{
$curl = curl_init(); // 啟動(dòng)一個(gè)CURL會(huì)話
curl_setopt($curl, CURLOPT_URL, $url); // 要訪問的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對(duì)認(rèn)證證書來源的檢測
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 從證書中檢查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解決數(shù)據(jù)包大不能提交
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動(dòng)跳轉(zhuǎn)
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動(dòng)設(shè)置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 發(fā)送一個(gè)常規(guī)的Post請(qǐng)求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的數(shù)據(jù)包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 設(shè)置超時(shí)限制防止死循
curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示返回的Header區(qū)域內(nèi)容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 獲取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 執(zhí)行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);
}
curl_close($curl); // 關(guān)鍵CURL會(huì)話
return $tmpInfo; // 返回?cái)?shù)據(jù)
}
?>