url 转 base64
原理: 利用 canvas.toDataURL 的 API 转化成 base64
function urlToBase64(url) {
return new Promise ((resolve, reject) => {
let image = new Image();
image.onload = function() {
let canvas = document.createElement('canvas');
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
// 将图片插入画布并开始绘制
canvas.getContext('2d').drawImage(image, 0, 0);
// result
let result = canvas.toDataURL('image/png')
resolve(result);
};
// CORS 策略,会存在跨域问题 https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
image.setAttribute('crossOrigin', 'Anonymous');
image.src = url;
// 图片加载失败的错误处理
image.onerror = () => {
reject(new Error('urlToBase64 error'));
};
}
}
使用:
let imgUrL = `http://XXX.jpg`
urlToBase64(imgUrL).then(res => {
// 转化后的base64图片地址
console.log('base64', res)
})
blob 转 url
原理: 利用 URL.createObjectURL 为 blob 对象创建临时的 URL
let url = URL.createObjectURL(blob)
blob 转 base64
原理: 利用 fileReader 的 readAsDataURL,将 blob 转为 base64
blobToBase64(blob) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
};
// readAsDataURL
fileReader.readAsDataURL(blob);
fileReader.onerror = () => {
reject(new Error('blobToBase64 error'));
};
});
}
使用:
blobToBase64(blob).then(res => {
// 转化后的base64
console.log('base64', res)
})
base64 转 Blob
原理: Uint8Array,ArrayBuffer 构造
function base64toBlob(dataurl) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
或者
function baseToBlob (b64) {
const byteCharacters = atob(b64)
const byteNumbers = new Array(byteCharacters.length)
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers)
const blob = new Blob([byteArray], { type: 'image/jpeg' })
return blob
}
//需要你手动去掉 data:image/png;base64,
使用:
let base64Str = "data:image/png;base64,iVBORw0KGgoA.....AAANSUhEUgAA"
dataURLtoBlob(base64Str)
或者,利用 fetch(推荐)
fetch(`data:${type};base64,${base64}`).then(res => res.blob())
字符串 和 base64 之间互转
原理:atob 和 btoa
let str = btoa("Dsgsg1234567890-=[];'m,,./")
console.log(str) //RHNnc2cxMjM0NTY3ODkwLT1bXTsnbSwsLi8=
console.log(atob(str)) //Dsgsg1234567890-=[];'m,,./
blob 转 File
function blobToFile(blob, name) {
return new File([blob], name + '.png', { type: blob.type });
}
网友评论