[Javascript]Synchronously converting between DataURL and Blob

dataurl and blob

In this article, we will discuss how to perform synchronous conversion from DataURL to Blob and from Blob to DataURL.



DataURL to Blob

const dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjOHLkyH8AB+gDTOQq89IAAAAASUVORK5CYII="
const blob = dataUrl2Blob(dataUrl)


function dataUrl2Blob(dataUrl) {
    const str = atob(dataUrl.split(',')[1])
    const type = dataUrl.match(/:([a-z/-]+);/)[1]
    const buffer = new Uint8Array(str.split('').map(c => c.charCodeAt(0))).buffer
    return new Blob([buffer], {type: type})
}





Blob to DataURL

const blob = new Blob(['hoge'], {type: 'image/png'})
const dataUrl = convert2DataUrl(blob)


function convert2DataUrl(fileOrBlob){
    const url = URL.createObjectURL(fileOrBlob)
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, false)
    xhr.overrideMimeType('text/plain; charset=x-user-defined')
    xhr.send()
    URL.revokeObjectURL(url)
    const data = xhr.responseText.split('').map(c => String.fromCharCode(c.charCodeAt(0)&0xff)).join('')
    return `data:${fileOrBlob.type};base64,` + btoa(data)
}






That is all, it was about how to perform synchronous conversion from DataURL to Blob and from Blob to DataURL.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*