Img、File、Base64类型互相转换
1.转File对象
let files = new window.File([bits], file.name, {type: file.type})
bits img/Blob/base64 格式图片
2.File对象转base64
封装
async fileToBase64(file) {
/*
file File对象
*/
let reader = new FileReader();
let fn = function() {
return new Promise((resolve) => {
reader.onload = function() {
let obj = {
code: 200,
data: this.result,
msg: '成功'
}
resolve(obj)
}
reader.onerror = function() {
let obj = {
code: 100,
data: '',
msg: '失败'
}
resolve(obj)
}
})
}
reader.readAsDataURL(file)
let res = await fn()
return res
}
调用
async upload(Files) {
let res = await file.fileToBase64(Files)
if(res.code == 200) {
// 成功
} else if(res.code == 100) {
// 失败
console.log(res.msg)
}
}
3.img转Blob对象
// url img地址,图片地址如果是网络图片,网络地址需要处理跨域 // fn 函数,返回一个blob对象 imageToBlob (url, fn) { if (!url || !fn) return false; var xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.responseType = 'blob'; xhr.onload = function () { // 注意这里的this.response 是一个blob对象 就是文件对象 fn(this.status == 200 ? this.response : false); } xhr.send(); return true; }
4.img转Base64
// 将图片转换为Base64 function imageUrlToBase64(img, fn) { // 一定要设置为let,不然图片不显示 let image = new Image(); // 解决跨域问题 image.setAttribute('crossOrigin', 'anonymous'); let imageUrl = img; image.src = imageUrl; // image.onload为异步加载 image.onload = () => { let canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; let context = canvas.getContext('2d'); // 解决图片转base64透明部分填充成黑色问题 context.fillStyle = "#fff"; context.fillRect(0, 0, canvas.width, canvas.height); context.drawImage(image, 0, 0, image.width, image.height); let quality = 0.8; // 这里的dataurl就是base64类型 let dataURL = canvas.toDataURL('image/jpeg', quality); fn(dataURL); }; }