Problems encountered: The image returned by the backend is base64 format, and the front end gets the return body and splices it and displays it on the IMG label. Wechat long press the image to save it, and it is found that apple long press saves the image successfully, while Android long press saves the image in the album in black (and the format is damaged).
this.imgUrl = "data:image/jpeg; base64," + res.content.base64_image; <div class="img-box" ref="imageTofile"> <img :src="imgUrl" alt="" /> </div>Copy the code
Solution 1. Use the HTML2Canvas plug-in to redraw, and choose the rendering method according to the device, because Apple saves the html2Canvas drawing invalid
1. Download html2canvas
npm install --save html2canvas
Copy the code
2. Import html2canvas
import html2canvas from 'html2canvas';
Copy the code
3. Use html2canvas
this.imgUrl = "data:image/jpeg; base64," + res.content.base64_image; // This path can only save let ua = navigator.userAgent; let isAndroid = ua.indexOf("Android") > -1 || ua.indexOf("Linux") > -1; If (isAndroid) {// If android, use html2Canvas to draw html2Canvas (this.$refs.imageTofile, {//this.$refs.imageTofile is my img's parent box backgroundColor: null, useCORS: true, // Resolve cross-domain windowWidth: document.body.scrollWidth, windowHeight: document.body.scrollHeight, x: this.$refs.imageTofile.offsetLeft, y: this.$refs.imageTofile.offsetTop, cale: }). Then ((canvas) => {let url = canvas.todataurl ('image/ PNG '); this.imgUrl = url }) }Copy the code
2. Redraw using native Canvas (advantage: no need to choose rendering method according to device,ios/ Android compatible)
1. Create a Canvas container on the page and set it to hide
<canvas v-show="false" ref="picture"></canvas>
Copy the code
2. Redraw and assign values using canvas
this.imgUrl = "data:image/jpeg; base64," + res.content.base64_image; // let img = new Image(); img.src = this.imgUrl; this.$nextTick(() => { let canvas = this.$refs.picture; // Get the canvas DOM let CTX = canvas.getContext('2d'); Img. onload = () => {canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); ImgUrl let canvasURL = canvas.toDataURL('image/jpeg'); this.imgUrl = canvasURL; }})Copy the code