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

Royjad
  • 99
  • 3
  • 13

1 Answers1

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')
Narendra
  • 4,514
  • 2
  • 21
  • 38
  • btoa() isn't defined in nodejs. I think it works in plain javascript. – Royjad Nov 13 '18 at 20:27
  • True, for that you need to use Buffer. – Narendra Nov 13 '18 at 20:37
  • 1
    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. https://www.site24x7.com/tools/datauri-to-image.html any thoughts ? – Royjad Nov 14 '18 at 04:17
  • which version of node are you using? is it possible for you to test the raw binary if that is valid? – Narendra Nov 14 '18 at 04:21
  • 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. https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/profilephoto_get – Royjad Nov 14 '18 at 20:46