Recently do a small program to upload pictures when base64 always reported upload pictures failed to investigate its reason is that the picture is too large to be compressed

So without further ado, let’s get to the code

After selecting the image, redraw the image size using canvas

Hide the canvas with absolute positioning

 <image class="uploader_input_icon" src="/images/wy/[email protected]" />
 <canvas canvas-id="canvas" style="width:{{cWidth}}px; height:{{cHeight}}px; position: absolute; left:-1000px; top:-1000px;"></canvas>Copy the code

Because there’s a lot of code to upload and compress, it’s extracted as a public method

Const chooseImage = (_this) => {wx.chooseImage({count: 1, // default 9 sizeType: ['compressed'], // Specify that only compressed graphs can be compressed, and do a default compression firstsourceType: ['album'.'camera'], // You can specify whether the source is photo album or camera, and default to both success: Photo => {// Add tempFilePaths[0] to the images array as a display _this.data.images.push(photo.tempfilepaths [0]) _this.setData({images: _this.data.images}) //----- Returns a list of local file paths for selected photos to obtain photo information ----------- wx.getimageinfo ({SRC: photo.tempfilepaths [0], success: Res = > {/ / -- -- -- -- -- -- -- -- -- use canvas compressed images -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var thewire = 2; Var canvasWidth = res.width var canvasHeight = res.heightwhile(canvasWidth > 400 | | canvasHeight > 400) {/ / that wide high canvasWidth within 400 = math.h trunc (res) width/thewire) canvasHeight = Math.trunc(res.height / ratio) ratio++; } _this.setData({ cWidth: canvasWidth, cHeight: CanvasHeight}) / / -- -- -- -- -- -- -- -- -- -- drawing graphics and extract image path -- -- -- -- -- -- -- -- -- -- -- -- -- - var CTX = wx. CreateCanvasContext ('canvas')
                    ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                    ctx.draw(false.setTimeout(function() {
                        wx.canvasToTempFilePath({
                            canvasId: 'canvas'DestWidth: canvasWidth, destHeight: canvasHeight, success: res => {console.log(res.tempFilepath) // Final image pathlet path = res.tempFilePath
                                let arr = path.split('. ');
                                letlist = {}; // get the imageType list.imagetype ='. '+ arr[arr.length - 1]; Base64Code list.base64Code = wx.getFilesystemManager ().readfilesync (path,'base64'); Console. log(list, _this.data.images) // Add list to imageList array as background interface parameter _this.data.imagelist.push (list)}, fail: Res => {console.log(res.errmsg)}})}, 100))}, // Leave some time to draw canvas fail: res => { console.log(res.errMsg) } }) } }) } module.exports = { chooseImage }Copy the code

When used, only import

let uploader = require('.. /utils/uploader') data:{images: [], imageList: []} // Uploader.chooseImage (this)Copy the code