file、blob、canvas、dataUrl几种对象之间的转换
function readBlobAsDataURL (blob|file, callback) {
let fr = new FileReader()
fr.onload = function (e) {
callback && callback(e.target.result)
}
fr.readAsDataURL(blob)
}
canvas.toDataURL('image/png'|'image/jpeg',0.8)
function dataURLtoBlob (dataurl) {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
function dataURLtoFile (dataurl, filename) {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], filename, { type: mime })
}
function formateFileSize(fileSize) {
if (fileSize === 0) {
return '0.0M'
}
if (fileSize < 1024) {
return `${fileSize}B`
} else if (fileSize < 1024 * 1024) {
return `${(fileSize / 1024).toFixed(2)}KB`
} else if (fileSize < 1024 * 1024 * 1024) {
return `${(fileSize / 1024 / 1024).toFixed(2)}MB`
} else {
return `${(fileSize / 1024 / 1024 / 1024).toFixed(2)}GB`
}
}
网友评论