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