How to convert binary image data to URI for same image in nodejs?
Asked Answered
F

1

3

I am using one API to get a profile photo of a user. This api gets me the binary data for a profile photo.

I need to be able to use this profile photo in form of a https://en.wikipedia.org/wiki/Data_URI_scheme

example:- json that will render an image where value of url should be URI.

{
    "type": "AdaptiveCard",
    "version": "1.0",
    "body": [
        {
            "type": "Image",
            "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAABfUlEQVRIS72UPU/DMBRF+69hYaJIbBUjfwFRkFCLKFH4iBQWOpeJbMBG5kzGJ+pLbOeFhKbhSkdW/O57t07dTowx/4K6OQaNjfXry9rK7IHInRuGaA011EM0n4PMrkLSNF1bzAhchEGaaTCceuegz68Pdb+NnYI2mzcay1WrazDfC0qSp06KoqCxXLW6BvOrIM0QIqcR8az5Qqz6BXFNGSqnEfHMPnWtT7Dyg57jRxPHcbnyhYeDu4SfPmYIDwm/WydICqvovlwJzvMcU2/hp09mCVbNoOhuVRn+EoaPHj6oILOs6iC36JoxdoVpIS5WfpCEhGHhbQtF3fW7MMuqeSKNLMswt4q61idY1UHL5cK0Eb467VnrE6z6Bck15+pyQdhj5RlRD3tcrLqDeMfyJ6rV2aeOT6uDF3Rze2WuF/uHuV6QZtoXXpBNPmeTT/Ab7itpq7NKyOV8fuAFAVdxWxzMds67zPaCYHY2O52eTM1Avo+OD8uTCF7IeJjJD3xajPLilAzRAAAAAElFTkSuQmCC",
            "style": "person"
        }
   ]
}

How can I convert binary image data to URI for same image in nodejs ?? so i can put it as a value of URI

Finnigan answered 13/11, 2018 at 3:55 Comment(1)
check this: https://mcmap.net/q/66791/-convert-blob-to-base64Dynamotor
D
4

You need to use btoa().

const imagData = 'data:image/png;base64,' + btoa('your-binary-data');

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

Buffer.from('your-binary-data').toString('base64')
Dignity answered 13/11, 2018 at 4:2 Comment(5)
btoa() isn't defined in nodejs. I think it works in plain javascript.Finnigan
True, for that you need to use Buffer.Dignity
I used following code to get URI using buffer. Body = raw image byte received from rest API. var buf = Buffer.from(body); var base64Data = buf.toString('base64') const imageURI = 'data:image/png;base64,' + base64Data; Then i used online convertor to test my URI & it didn't converted to image. I'm guessing this base64 isn't correct. I used another online converter which gives base64 using direct image upload & that works. site24x7.com/tools/datauri-to-image.html any thoughts ?Finnigan
which version of node are you using? is it possible for you to test the raw binary if that is valid?Dignity
Hi Narendra I'm on node v10.10.0 I am using following API to get binary. I confirmed it used REST client Postman & it does gives me image back. In nodejs app it shows me raw bytes which I pass it to Buffer. developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/…Finnigan

© 2022 - 2024 — McMap. All rights reserved.