Search code examples
javascriptbase64pngresponse

Create new Response from base64 image data with Javascript


I want to fake a response. I have the base64 string data of a png image. Now I want to make a response but It does not work.

My code:

const data = "data:image/png;base64,iVBORw0KGgoAAAA...";
const res = new Response(data, {
      status: 200,
      statusText: "OK",
      headers: {
        "Content-Type": "image/png",
        "Content-Length": data.length
      },
    });

I did some research, and it seems like base64 can not just be passed to response body. It needs to be converted to a buffer or something like that.

It can be done in NodeJS like this Buffer.from(data, 'base64')

But my code is in the browser only.

Is there any way that I can implement this.


Solution

  • base64 is an encoded string, to get the actual image you need to convert it to binary data using atob. here is an example:

    const b64String = data.split(',')[1];
    var byteString = atob(b64String);
    var arrayBuffer = new ArrayBuffer(byteString.length);
    var intArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    var imageBlob = new Blob([intArray], {type: 'image/png'});
    const res = new Response(imageBlob, {
      status: 200,
      statusText: "OK",
      headers: {
        "Content-Type": "image/png",
        "Content-Length": imageBlob.size
      },
    });