Search code examples
javascriptreactjsimagewhatsappdata-uri

How to extract data URL from image binary data received from WhatsApp API?


Requirement

I am using WhatsApp API to receive and send messages. Now, someone sent me an image and the response I am getting by API is in the form of binary data as shown in the screenshot below.

enter image description here

(and ofcourse the binary data is far more lengthy than the screenshot)

My requirement is to convert this string to Data URL so that I can display it in the browser.

#######################################################################

What I have tried

I have tried the following as per googling for a bit but it is not helping.

const extractedImage = `data:${mimeType};base64,${Buffer.from(response.data).toString("base64")}`;
// where response.data gives the binary data of image and mimeType is image/jpeg

The string after the above conversion is as displayed below.

enter image description here

The Data URL is not valid and I am getting a blank output. Please guide me how to resolve this problem.


Solution

  • I have figured out the solution.

    Just needed to mention

    responseType: "arrayBuffer", responseEncoding: "binary"
    

    while making the Axios API call and also adding "binary" parameter while converting to "base64"

    Buffer.from(response.data, "binary").toString("base64");
    

    Reference -> Check out the last comment by Andrew here