1. 点击选择图片/拍照
// 点击拍照/选择图片 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) } }) },
2.将图片处理成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) } }); } },
3. 把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 }) },
4. 点击预览图片
previewImage: function(e) { var that = this, //获取当前图片的下表 index = e.currentTarget.dataset.index, //数据源 pictures = this.data.base64ImgUrl; wx.previewImage({ //当前显示下表 current: pictures[index], //数据源 urls: pictures }) },
5. wxml部分
工作证