Blob from DataURL?

JavascriptFileapi

Javascript Problem Overview


Using FileReader's readAsDataURL() I can transform arbitrary data into a Data URL. Is there way to convert a Data URL back into a Blob instance using builtin browser apis?

Javascript Solutions


Solution 1 - Javascript

User Matt has proposed the following code a year ago ( https://stackoverflow.com/questions/6850276/how-to-convert-dataurl-to-file-object-in-javascript ) which might help you

EDIT: As some commenters reported, BlobBuilder has been deprecated some time ago. This is the updated code:

function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);

  // create a view into the buffer
  var ia = new Uint8Array(ab);

  // set the bytes of the buffer to the correct values
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {type: mimeString});
  return blob;

}

Solution 2 - Javascript

Like @Adria method but with Fetch api and just smaller [caniuse?]
Don't have to think about mimetype since blob response type just works out of the box

> Warning: Can violate the Content Security Policy (CSP)
> ...if you use that stuff

var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(blob => console.log(blob))

Don't think you could do it any smaller then this without using lib's

Solution 3 - Javascript

In modern browsers one can use the one liner suggested by Christian d'Heureuse in a comment:

const blob = await (await fetch(dataURI)).blob(); 

Solution 4 - Javascript

dataURItoBlob : function(dataURI, dataTYPE) {
		var binary = atob(dataURI.split(',')[1]), array = [];
		for(var i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
		return new Blob([new Uint8Array(array)], {type: dataTYPE});
	}

input dataURI is Data URL and dataTYPE is the file type and then output blob object

Solution 5 - Javascript

XHR based method.

function dataURLtoBlob( dataUrl, callback )
{
	var req = new XMLHttpRequest;

	req.open( 'GET', dataUrl );
	req.responseType = 'arraybuffer'; // Can't use blob directly because of https://crbug.com/412752

	req.onload = function fileLoaded(e)
	{
		// If you require the blob to have correct mime type
		var mime = this.getResponseHeader('content-type');

		callback( new Blob([this.response], {type:mime}) );
	};

	req.send();
}

dataURLtoBlob( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', function( blob )
{
	console.log( blob );
});

Solution 6 - Javascript

try:

function dataURItoBlob(dataURI) {
    if(typeof dataURI !== 'string'){
        throw new Error('Invalid argument: dataURI must be a string');
    }
    dataURI = dataURI.split(',');
    var type = dataURI[0].split(':')[1].split(';')[0],
        byteString = atob(dataURI[1]),
        byteStringLength = byteString.length,
        arrayBuffer = new ArrayBuffer(byteStringLength),
        intArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteStringLength; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    return new Blob([intArray], {
        type: type
    });
}

Solution 7 - Javascript

Since none of these answers support base64 and non-base64 dataURLs, here's one that does based on vuamitom's deleted answer:

// from https://stackoverflow.com/questions/37135417/download-canvas-as-png-in-fabric-js-giving-network-error/
var dataURLtoBlob = exports.dataURLtoBlob = function(dataurl) {
    var parts = dataurl.split(','), mime = parts[0].match(/:(.*?);/)[1]
    if(parts[0].indexOf('base64') !== -1) {
        var bstr = atob(parts[1]), n = bstr.length, u8arr = new Uint8Array(n)
        while(n--){
            u8arr[n] = bstr.charCodeAt(n)
        }

        return new Blob([u8arr], {type:mime})
    } else {
        var raw = decodeURIComponent(parts[1])
        return new Blob([raw], {type: mime})
    }
}

Note: I'm not sure if there are other dataURL mime types that might have to be handled differently. But please let me know if you find out! Its possible that dataURLs can simply have any format they want, and in that case it'd be up to you to find the right code for your particular use case.

Solution 8 - Javascript

Create a blob using XHR API:

function dataURLtoBlob( dataUrl, callback )
{
    var req = new XMLHttpRequest;

    req.open( 'GET', dataUrl );
    req.responseType = 'blob';

    req.onload = function fileLoaded(e)
    {
        callback(this.response);
    };

    req.send();
}

var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

dataURLtoBlob(dataURI , function( blob )
{
    console.log( blob );
});

Solution 9 - Javascript

Use my code convert dataURI to blob. It's simpler and cleaner than others.

function dataURItoBlob(dataURI) {
    var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1];
    return new Blob([atob(arr[1])], {type:mime});
}

Solution 10 - Javascript

If you need something that works server-side on Google Apps Script, try:

function dataURItoBlob(dataURI) {
  // convert base64 to Byte[]
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var data = Utilities.base64Decode(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  var blob = Utilities.newBlob(data);
  blob.setContentType(mimeString);
  return blob;
}

Solution 11 - Javascript

use

FileReader.readAsArrayBuffer(Blob|File)

rather than

FileReader.readAsDataURL(Blob|File)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShane HollowayView Question on Stackoverflow
Solution 1 - Javascriptdevnull69View Answer on Stackoverflow
Solution 2 - JavascriptEndlessView Answer on Stackoverflow
Solution 3 - JavascriptJan DerkView Answer on Stackoverflow
Solution 4 - JavascriptShawn WuView Answer on Stackoverflow
Solution 5 - JavascriptAdriaView Answer on Stackoverflow
Solution 6 - JavascriptHaNdTriXView Answer on Stackoverflow
Solution 7 - JavascriptB TView Answer on Stackoverflow
Solution 8 - JavascriptgeorgeawgView Answer on Stackoverflow
Solution 9 - JavascriptcuixipingView Answer on Stackoverflow
Solution 10 - JavascriptTilman VogelView Answer on Stackoverflow
Solution 11 - Javascript3onView Answer on Stackoverflow