Skip to content

Instantly share code, notes, and snippets.

@maruware
Forked from wuchengwei/dataURL to blob and blob to dataURL
Last active January 19, 2022 01:28
Show Gist options
  • Save maruware/8213050fc987fbc1b98650467f518261 to your computer and use it in GitHub Desktop.
Save maruware/8213050fc987fbc1b98650467f518261 to your computer and use it in GitHub Desktop.
dataURL to blob and blob to dataURL
//**dataURL to blob**
function dataURLtoBlob(dataurl: string) {
const arr = dataurl.split(',')
const fmt = arr[0]
const b64 = arr[1]
if (!fmt || !b64) throw new Error('invalid dataurl')
const m = fmt.match(/:(.*?);/)
if (!m) throw new Error('invalid dataurl')
const mime = m[1]
if (!mime) throw new Error('invalid dataurl')
const bstr = atob(b64)
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
//**blob to dataURL**
function blobToDataURL(blob: Blob, callback: (dataurl: string) => void) {
const a = new FileReader()
a.onload = (e) => {
callback(e.target!.result as string)
}
a.readAsDataURL(blob)
}
//test:
const blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');
blobToDataURL(blob, function(dataurl){
console.log(dataurl)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment