0

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

quefro
  • 101
  • 4
  • 12

2 Answers2

2

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)
omeanwell
  • 1,847
  • 1
  • 10
  • 16
0
    const processFile = (file: any) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function(){
      const binaryData = Buffer.from(reader.result as string,'binary');
      console.log(binaryData);
    };
  }
  • Please don't post code-only answers. Future readers will be grateful to see explained *why* this answers the question instead of having to infer it from the code. Also, since this is an old question, please explain how it compliments the other answer. – Gert Arnold May 26 '22 at 18:44