convert base64 to blob and store it in a variable in javascript

To convert a Base64-encoded string to a Blob and store it in a variable in JavaScript, you can use the atob function to decode the Base64 string into a binary string, and then create a new Blob object using the binary string and the content type of the data. Here's an example:

index.tsx
// Base64-encoded string
var base64str = "data:image/png;base64,iVBORw0KGg...";

// Decode the Base64 string into a binary string
var binarystr = atob(base64str.split(",")[1]);

// Convert the binary string to an ArrayBuffer
var arraybuffer = new ArrayBuffer(binarystr.length);
var uint8 = new Uint8Array(arraybuffer);
for (var i = 0; i < binarystr.length; i++) {
    uint8[i] = binarystr.charCodeAt(i);
}

// Create a new Blob object using the ArrayBuffer and content type of the data
var blob = new Blob([arraybuffer], {type: "image/png"});
543 chars
16 lines

In this example, base64str is the Base64-encoded string that you want to convert to a Blob. The atob function is used to decode the Base64 string into a binary string, which can then be converted to an ArrayBuffer. Finally, a new Blob object is created using the ArrayBuffer and content type of the data. The resulting Blob object can be stored in a variable for later use.

gistlibby LogSnag