1.在线转base64
//异步执行
imageUrlToBase64(url) {
console.log(url, "uel")
//一定要设置为let,不然图片不显示
let image = new Image();
//解决跨域问题
image.setAttribute('crossOrigin', 'anonymous');
image.src = url
console.log(image, "image")
//image.onload为异步加载
image.onload = () => {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
var quality = 0.8;
//这里的dataurl就是base64类型
var dataURL = canvas.toDataURL("image/jpeg",
quality); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
this.saveImg(dataURL)
}
},
2.下载
saveImg(url) {
var oA = document.createElement("a");
oA.download = ''; // 设置下载的文件名,默认是'下载'
oA.href = url;
document.body.appendChild(oA);
oA.click();
oA.remove(); // 下载之后把创建的元素删除
},
网友评论