[英]How to convert image.png to binary in NodeJS?
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 .我正在尝试使用 Azure Forms 识别器 API,其中我必须以此处所述的“[二进制 PNG 数据]”的形式提供正文。 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."}}
{"error":{"code":"InvalidImage","innerError":{"requestId":"73c86dc3-51a3-48d8-853b-b6411f54c51e"},"message":"输入数据不是有效图像或密码保护。”}}
I am using a png that is my local directory and I've tried converting it in many different ways including:我使用的是我的本地目录 png,我尝试以多种不同方式对其进行转换,包括:
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.如果有人可以分享如何将此 png 转换为正确的格式,我将不胜感激。 Thank you in advance
先感谢您
To base 64:以 64 为基数:
const file = fs.readFileSync('/some/place/image.png')
const base64String = Buffer.from(file).toString('base64')
Then pass the base64String to Azure然后将base64String传递给Azure
If you want just a BLOB so a binary file, you can do this如果你只想要一个 BLOB 所以一个二进制文件,你可以这样做
const file = fs.readFileSync('/some/place/image.png')
const blob = Buffer.from(file)
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);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.