1 <template> 2 <view class="content"> 3 <view @tap="ChooseImage()">点击上传图片</view> 4 </view> 5 </template> 6 7 <script> 8 export default { 9 data() { 10 return { 11 title: ‘Hello‘ 12 } 13 }, 14 onLoad() { 15 16 }, 17 methods: { 18 ChooseImage() { 19 uni.chooseImage({ 20 count: 1, 21 sizeType: [‘original‘, ‘compressed‘], //可以指定是原图还是压缩图,默认二者都有 22 sourceType: [‘album‘], //从相册选择 23 success: res => { 24 const imgSize = res.tempFiles[0] && res.tempFiles[0].size ? res.tempFiles[0].size : 0; 25 const imgName = res.tempFiles[0]&&res.tempFiles[0].name?res.tempFiles[0].name:‘‘; 26 console.log(imgSize) 27 this.photoCompress(res.tempFiles[0], (base64Codes) => { 28 var fl = this.dataURLtoFile(base64Codes,imgName) 29 console.log(fl, "压缩后的文件") 30 }) 31 } 32 }) 33 }, 34 photoCompress(file, objDiv) { 35 var ready = new FileReader(); 36 ready.readAsDataURL(file); 37 const _this = this; 38 ready.onload = function() { 39 var fileResult = this.result; 40 _this.canvasDataURL(fileResult, objDiv) 41 } 42 }, 43 canvasDataURL(path, callback) { 44 var img = new Image(); 45 img.src = path; 46 var objCompressed = {} 47 img.onload = function() { 48 var that = this; 49 //默认压缩后图片规格 50 var quality = 0.7; 51 var w = that.width; 52 var h = that.height; 53 var scale = w / h; 54 //实际要求 55 w = objCompressed.width || w; 56 h = objCompressed.height || (w / scale); 57 //生成canvas 58 var canvas = document.createElement(‘canvas‘); 59 var ctx = canvas.getContext(‘2d‘); 60 // 创建属性节点 61 var anw = document.createAttribute("width"); 62 anw.nodeValue = w; 63 var anh = document.createAttribute("height"); 64 anh.nodeValue = h; 65 canvas.setAttributeNode(anw); 66 canvas.setAttributeNode(anh); 67 ctx.drawImage(that, 0, 0, w, h); 68 69 var base64 = canvas.toDataURL(‘image/jpeg‘, quality); 70 // 回调函数返回base64的值 71 callback(base64); 72 } 73 }, 74 dataURLtoFile(dataurl,filename) { 75 var arr = dataurl.split(","), 76 mime = arr[0].match(/:(.*?);/)[1], 77 bstr = atob(arr[1]), 78 n = bstr.length, 79 u8arr = new Uint8Array(n); 80 while (n--) { 81 u8arr[n] = bstr.charCodeAt(n); 82 } 83 return new File([u8arr],filename, { type: mime }); 84 } 85 } 86 } 87 </script> 88 89 <style> 90 91 </style>