Home >Web Front-end >JS Tutorial >How to Create a Blob from a Base64 String in JavaScript?
You have base64-encoded binary data in a string and want to create a Blob URL containing this data and display it to the user. Specifically, the goal is to create a Blob object from the base64 string, as seen in the code snippet below:
const blob = new Blob(????, {type: contentType}); const blobUrl = URL.createObjectURL(blob);
To decode a base64 string to a Blob object in JavaScript, follow these steps:
Decode the base64 data: Use the atob function to decode the base64 string into a character string:
const byteCharacters = atob(b64Data);
Convert byte characters to byte values: Create an array of byte values by getting the character code point (charCode) for each character in the string:
const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); }
Create a typed byte array: Convert the byte values into a real typed byte array using the Uint8Array constructor:
const byteArray = new Uint8Array(byteNumbers);
Wrap in an array and create Blob: Create a Blob object by wrapping the byte array in an array and passing it to the Blob constructor:
const blob = new Blob([byteArray], {type: contentType});
The code above is fully functional, but performance can be improved by slicing the byte characters into smaller chunks before processing.
Here's a full example, creating an image element from the Blob:
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; }; const contentType = 'image/png'; const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; const blob = b64toBlob(b64Data, contentType); const blobUrl = URL.createObjectURL(blob); const img = document.createElement('img'); img.src = blobUrl; document.body.appendChild(img);
The above is the detailed content of How to Create a Blob from a Base64 String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!