前言:最近寫(xiě)了小程序二維碼,分享一下
前面只寫(xiě)了小程序端的實(shí)現(xiàn)(有人在評(píng)論指出),現(xiàn)在更新下兼容版本且预,主要實(shí)現(xiàn)還是在-圖像base64保存為文件,下面上一下兼容版本的
export function base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
應(yīng)用:
import { base64ToPath } from '@/common/plus.js'
base64ToPath(url).then(path=>{
console.log(path)
})
下面是從前的內(nèi)容
通過(guò)接口獲取token烙无,直接調(diào)取微信接口POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
這個(gè)方法在模擬器上可以實(shí)現(xiàn)锋谐,但是由于安全域名的配置不能是https://api.weixin.qq.com。截酷。怀估。所以必須由后臺(tái)獲取說(shuō)一下實(shí)現(xiàn):
獲取接口返回的數(shù)據(jù)(我這邊由后臺(tái)處理返回的是base64),然后把數(shù)據(jù)轉(zhuǎn)圖片文件合搅,由canvas畫(huà)出來(lái)(小程序的canvas繪制圖片,圖片路徑必須為本地的路徑)組件代碼(接口返回?cái)?shù)據(jù)處理):
import {getQrCode} from "@/api/spu.js"
//獲取小程序碼
getQrCode(this.option.path).then(res=>{
uni.showLoading({title: '正在生成圖片'});
this.base64ToPath(res.result,path=>{
console.log(path)
this.qrCodeRes = path
this.toDrawCanvas() //畫(huà)圖
})
})
- base64轉(zhuǎn)圖片文件代碼:
base64ToPath(path,success) {
let that = this
var fileName = Date.now() + '.' + 'png'
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: path,
encoding: 'base64',
success() {
success(filePath)
},
fail(error) {
that.$toast(error)
}
})
return
}
}
- 接口代碼:
//獲取微信小程序二維碼(接口)
export function getQrCode(path,success) {
let param = {
"page":"pages/product/detail/index",
"scene":path.split('?')[1],
"width":"280"
}
return apiBase('wx/getXcxQrCode',param,{showLoading:false,resAll:true})
}
好啦歧蕉,完成灾部。。惯退。撒花花~~~