toBase64(imgUrl) {
// 一定要设置为let,不然图片不显示
const image = new Image();
// 解决跨域问题
image.setAttribute('crossOrigin', 'anonymous');
const imageUrl = imgUrl;
image.src = imageUrl
// 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类型
// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
this.base64Url = canvas.toDataURL('image/jpeg', quality);
console.log(this.base64Url);
let newFile = this.base64ToFile(this.base64Url,'aa')
console.log(newFile);
}
},
base64ToFile(urlData, fileName) {
let arr = urlData.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]); // 解码base64
let n = bytes.length
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mime });
},
图片url转base64,base64转file
最新推荐文章于 2024-08-30 07:34:18 发布