var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
  var base64data = reader.result;                
  console.log(base64data);
}

Form the docs readAsDataURL encodes to base64

As an awaitable function:

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}

Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:/;base64, from the result.

Answer from Arun Killu on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 64348624 › angular2-convert-blob-to-long-base64
angular - Angular2 - Convert Blob to long base64 - Stack Overflow
var blob = new Blob([response], {type : "image/jpg"}), reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { console.log(reader.result); }; ... description: "URL [file:20201014_0822_05020362.jpg]" file: ...
Top answer
1 of 16
1181

The atob function will decode a base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method 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);
}

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a Blob by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

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 blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

Show code snippet

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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
666

Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)

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

fetch(url)
.then(res => res.blob())
.then(console.log)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)

As a function:

const b64toBlob = (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`).then(res => res.blob())

But I would encourage you to don't use base64 in the first place. There are better ways to send and receive binary data. JSON isn't always the best option. it takes up more bandwidth and waste processing time (de)encodeing stuff. Us eg canvas.toBlob instead of canvas.toDataURL and use FormData to send binary files. you can also return back a multipart payload and decode it using await response.formData() that is coming from a server response. FormData can go both ways.


I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while. keeping the devtool open can slow the fetch performance

Show code snippet

document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();


async function perf() {
  
  const blob = await fetch(img).then(res => res.blob())
  // turn it to a dataURI
  const url = img
  const b64Data = url.split(',')[1]

  // Jeremy Banks solution
  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;
  }

  // bench blocking method
  let i = 500
  console.time('blocking b64')
  while (i--) {
    await b64toBlob(b64Data)
  }
  console.timeEnd('blocking b64')
  
  // bench non blocking
  i = 500

  // so that the function is not reconstructed each time
  const toBlob = res => res.blob()
  console.time('fetch')
  while (i--) {
    await fetch(url).then(toBlob)
  }
  console.timeEnd('fetch')
  console.log('done')
}

perf()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
StackBlitz
stackblitz.com › edit › blob-base64-dataurl
Blob Base64 Dataurl - StackBlitz
Starter project for Angular apps that exports to the Angular CLI
🌐
Stack Overflow
stackoverflow.com › questions › 68368840 › how-to-convert-blob-image-to-base64-base64-variable-showing-up-as-null
angular - how to convert blob image to base64? base64 variable showing up as null - Stack Overflow
July 13, 2021 - @Component({ selector: 'home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], encapsulation: ViewEncapsulation.None }) export class HomeComponent implements OnInit { data:any image:any retrievedImage: any; base64Data: any; retrieveResonse: any; imageName:any; constructor(private imageData:imageService, private httpClient:HttpClient) { } ngOnInit(): void { console.log(this.image) this.imageData.getImages().subscribe((results)=>{ console.log(results) this.data = results }) } getImage2() { var reader = new FileReader(); //Make a call to Spring Boot to get the Image Byt
🌐
GitHub
gist.github.com › n1ru4l › dc99062577b746e0783410b1298ab897
Fetch blob and convert to base64 · GitHub
Fetch blob and convert to base64 · Raw · index.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 79496599 › file-blob-promise-storage-encode-decode-in-base64-in-typescript-html-comp
File, Blob, Promise, async/await, store images in FormData, encode/decode images in base64 .. in Typescript/HTML component - Angular 19
let fn = item.innerText.split(';')[0]; let ext = fn.slice(fn.lastIndexOf('.') + 1, fn.length); let p = await fetch(fn).then(response => response.blob()); let b = await p.arrayBuffer(); let ua = new Uint8Array(b) let u64 = ua.toBase64; let f0 = new File( ua , fn, { type: `image/${ext}` }); console.log(f0); const para = document.createElement("p"); para.textContent = item.textContent; preview.appendChild(para); var reader = new FileReader() reader.onload = function (e) { var image = document.createElement("img"); image.src = e.target.result; console.log(image.src); var bs = atob(e.target.result)
🌐
Webdevtutor
webdevtutor.net › blog › typescript-blob-base64
A Guide to Handling Blobs and Base64 in TypeScript
In TypeScript, Blobs are commonly used to represent files, such as images or documents, in their raw binary form. Blobs are useful for handling large amounts of binary data efficiently. To convert a Blob to Base64 in TypeScript, you can use the FileReader API.
🌐
Medium
geekjob.medium.com › convert-blob-to-base64-in-js-e5808fd69961
Convert Blob to Base64 in JS - Fullstack CTO - Medium
March 22, 2023 - Typescript · Fullstack CTO · Mar 21, 2023 · -- 1 · Listen · Share · No comment · const blob2base64 = (blob, mimeType) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { const dataUrlPrefix = `data:${mimeType};base64,`; const base64WithDataUrlPrefix = reader.result; const base64 = base64WithDataUrlPrefix.replace(dataUrlPrefix, ''); resolve(base64); }; reader.onerror = reject; reader.readAsDataURL(blob); }); }; const obj = { hello: 'world' }; const mimeType = 'application/json'; const blob = new Blob([JSON.stringify(obj, null, 2)], { type: mimeType }); blob2base64(blob, mimeType).then(base64 => { console.log(base64); }); // or const base64 = await blob2base64(blob, mimeType); console.log(base64); JavaScript ·
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Encode Blob to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
Another way to convert Blob to Base64 is to call reader.readAsBinaryString(blob) and use btoa(reader.result) to get the Base64 string.
🌐
JSFiddle
jsfiddle.net › wilt › 1u9fgyh0
From blob to base64 string - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
GitHub
gist.github.com › Marceloalves6 › d1f590437f7fe45ac6832e5177c84be6
Typescript method to convert string base64 to blob · GitHub
Typescript method to convert string base64 to blob · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Microsoft Learn
learn.microsoft.com › en-in › answers › questions › 695762 › mapping-datatype-to-angular
Mapping datatype to Angular. - Microsoft Q&A
var content= this.base64ToArrayBuffer(response.DocContent); var blob = new Blob([content], { type: response.ContentType });
🌐
IQCode
iqcode.com › code › other › how-to-convert-a-base-64-to-blob
how to convert a base 64 to blob Code Example
October 2, 2021 - import { base64StringToBlob } from 'blob-util'; const contentType = 'image/png'; const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNb...
🌐
Medium
abhayahire.medium.com › angular-view-blob-base64-image-and-print-pdf-33b8e7dfaecd
Angular View Blob (Base64) Image and Print PDF | by Abhay Ahire | Medium
August 14, 2022 - Let’s generate angular application from scratch Use ng new print-pdfcommand to create new angular project. Now as first thing we need to show image into browser. We have added static base64 encoded string into assets folder within data.json file. You can check github link to see the contents.