一、点击选择图片/拍照
// 点击拍照/选择图片
choosePic() {
let that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// 将图片处理成base64
that.transformBase(res);
},
fail: function(res) {
console.log(res.errMsg)
}
})
},
二、将图片处理成base64
transformBase(res) {
let that = this;
var FSM = wx.getFileSystemManager();
//循环将得到的图片转换为Base64
for (let r in res.tempFilePaths) {
// console.log(res.tempFilePaths[r])
FSM.readFile({
filePath: res.tempFilePaths[r],
encoding: "base64",
success: function(data) {
let Working = data.data;
that.getBase64ImageUrl(Working)
}
});
}
},
三、把base64转成图片路径显示在页面
getBase64ImageUrl: function(res) {
/// 获取到base64Data
var base64Data = res;
/// 通过微信小程序自带方法将base64转为二进制去除特殊符号,再转回base64
base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
/// 拼接请求头,data格式可以为image/png或者image/jpeg等,看需求
let base64ImgUrl = this.data.base64ImgUrl;
let WorkingCard = this.data.WorkingCard; //需要赋值的图片base64字段
let base64Url = "data:image/png;base64," + base64Data;
base64ImgUrl.push(base64Url); //用来显示在页面上的base64路径(数组)
WorkingCard = base64Url;
// 获取文件(图片)MD5
let dealToMD5 = sMD5.hexMD5(base64Url); //(var sMD5 = require('../../utils/common/spark-md5.js'))
/// 刷新数据
// console.log(base64ImgUrl, '===========')
this.setData({
isGetPicture: true,
base64ImgUrl: base64ImgUrl,
WorkingCard: WorkingCard,
WorkingCardMD5: dealToMD5
})
},
四、点击预览图片
previewImage: function(e) {
var that = this,
//获取当前图片的下表
index = e.currentTarget.dataset.index,
//数据源
pictures = this.data.base64ImgUrl;
wx.previewImage({
//当前显示下表
current: pictures[index],
//数据源
urls: pictures
})
},
html部分
<cus-itemLine type="normal registerCard">
<view class="lineLeft">工作证</view>
<view class="lineCard">
<view class="delete" bindtap="deleteShopPhoto" wx:if="{{isGetPicture}}">
<view class="deleteBtn">
<image class="deleteIcon" src="../../images/deletePic.png"></image>
</view>
</view>
<image class="Icon" src="{{isGetPicture?base64ImgUrl[0]:'../../images/workPic.png'}}" bindtap="{{isGetPicture?'previewImage':'choosePic'}}" data-index="{{base64ImgUrl[0]}}"></image>
</view>
</cus-itemLine>
参考:https://blog.csdn.net/qq_38244984/article/details/82221151
https://blog.csdn.net/weixin_34128411/article/details/88120030
https://blog.csdn.net/gao_xu_520/article/details/72724008
网友评论