安卓微信中长按base64图片无法保存的解决办法
遇到的问题:后端返回的是base64格式的图片,前端拿到返回体后进行拼接展示在img标签上,微信长按图片进行保存,发现苹果长按保存成功,安卓长按保存后相册中保存的图片时黑色的(且提示格式损坏)
解决办法,使用html2canvas插件进行重新绘制,根据设备来选择渲染方法
1.下载html2canvas
1 npm install --save html2canva
2.导入html2canvas
1 import html2canvas from 'html2canvas';
3.使用html2canvas
1 this.imgUrl = "data:image/jpeg;base64," + res.content.base64_image; 2 3 4 let ua = navigator.userAgent; 5 let isAndroid = ua.indexOf("Android") > -1 || ua.indexOf("Linux") > -1; //判断设备是不是安卓 6 if (isAndroid) { //如果是安卓,则使用html2canvas绘制 7 html2canvas(this.$refs.imageTofile, { //this.$refs.imageTofile是我的img的父盒子 8 backgroundColor: null, 9 useCORS: true, //解决跨域 10 windowWidth: document.body.scrollWidth, 11 windowHeight: document.body.scrollHeight, 12 x: this.$refs.imageTofile.offsetLeft, 13 y: this.$refs.imageTofile.offsetTop, 14 scale: 6, // 这是分辨率倍数,一般是2,越高图片越大,越清晰 15 }).then((canvas) => { 16 let url = canvas.toDataURL('image/png'); 17 this.imgUrl = url 18 }) 19 }
解决办法2.使用原生canvas进行重新绘制,(优点:不用根据设备来选择渲染方法,ios/安卓都能兼容)
1.页面上创建一个canvas容器,设置其隐藏
1 <canvas v-show="false" ref="picture"></canvas>
2.使用canvas重新绘制并赋值
1 this.imgUrl = "data:image/jpeg;base64," + res.content.base64_image;//这个路径只能苹果保存 2 3 let img = new Image(); 4 img.src = this.imgUrl; 5 this.$nextTick(() => { 6 let canvas = this.$refs.picture; //获取到canvas的DOM 7 let ctx = canvas.getContext('2d'); //使用2d绘图 8 img.onload = () => { 9 canvas.width = img.width; 10 canvas.height = img.height; 11 ctx.drawImage(img, 0, 0, img.width, img.height); //完整的将this.imgUrl给裁剪下来 12 let canvasURL = canvas.toDataURL('image/jpeg'); 13 this.imgUrl = canvasURL; 14 } 15 })