How to convert image.png to binary in NodeJS?

Issue

I am trying to consume Azure Forms Recognizer API, where I have to provide the body in the form of "[Binary PNG data]" as stated here.
The connection seems the be working fine, however I am getting this response:

{"error":{"code":"InvalidImage","innerError":{"requestId":"73c86dc3-51a3-48d8-853b-b6411f54c51e"},"message":"The input data is not a valid image or password protected."}}

I am using a png that is my local directory and I’ve tried converting it in many different ways including:

fs.readFile('test.png', function(err, data){
if (err) throw err;
// Encode to base64
let encodedImage = new Buffer(data, 'binary').toString('base64');
// Decode from base64
var decodedImage = new Buffer(encodedImage, 'base64').toString('binary');});

or

let data_string = fs.createReadStream('test.png');

and many others. None of them seem to work and I always get the same response from my post request.

I would appreciate if anyone could share how to convert this png into the correct format. Thank you in advance

Solution

To base 64:

const file = fs.readFileSync('/some/place/image.png')
const base64String = Buffer.from(file).toString('base64')

Then pass the base64String to Azure

If you want just a BLOB so a binary file, you can do this

const file = fs.readFileSync('/some/place/image.png')
const blob = Buffer.from(file)

Answered By – omeanwell

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.