[Javascript]DataURL to Blob and Blob to DataURL

dataurl and blob



In this article, I am going to describe about how to convert DataURL to Blob and how to convert Blob to DataURL.




DataURL to Blob

fetch method might be helpful to convert DataURL to Blob.
You can do any operation againt the returned blob in the then method.

let dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjOHLkyH8AB+gDTOQq89IAAAAASUVORK5CYII="
fetch(dataUrl)
.then(response => response.blob())
.then(blob => {
    console.log(blob)    //Blob object
})




DataURL to Blob as a function

In the way which I wrote above, we have to write the continuation in the then method.
By getting together the conversion process as a function as below, we can save the result into a variable.

;(async function(){
    //some code
    //some code

    let dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjOHLkyH8AB+gDTOQq89IAAAAASUVORK5CYII="
    let blob = await url2Blob(dataUrl)

    //some code
    //some code
})()

async function url2Blob(url){
    return await (await fetch(url)).blob()
}


Because the fetch method is asynchronous process, async/await is required to save the result into a variable. Details are explained in the below article.
[Javascript]How to save a fetch result into a variable








Blob to DataURL

FileReader might be helpful to convert Blob to DataURL.
You can do any operation againt the returned DataURL in the onload event.

let blob = new Blob(['hoge'],{type: 'image/png'})
let reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = function(){
    dataUrl = reader.result
    console.log(dataUrl)    //DataURL
}





Blob to DataURL as a function

In the way which I wrote above, we have to write the continuation in the onload event.
By getting together conversion process as a function as below, we can save the result into a variable.

;(async function(){
    //some code
    //some code

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

    //some code
    //some code
})()


async function convert2DataUrl(blobOrFile){
    let reader = new FileReader()
    reader.readAsDataURL(blobOrFile)
    await new Promise(resolve => reader.onload = function(){ resolve() })
    return reader.result
}


Because the FileReader is asynchronous process, async/await is required to save the result into a variable.
Though Promise is also used and little bit complecated, details are explained in the below article.
[Javascript]How to save FileReader result into a variable





That is all, it was about how to convert DataURL to Blob and how to convert Blob to DataURL.

Sponsored Link

You can subscribe by SNS

Sponcerd Link