我正在使用Node js使用azure face api,下面是代码。但是,而不是图像托管的一些地方,我想使用我的本地图像并将其发布。我尝试了其他选项,但无法识别图像格式或无效的图像
下面是我尝试过的事情
1) var stream = fs.createReadStream('local image url');
2) var imageAsBase64 = fs.readFileSync('image.jpg','base64');
下面是代码
'use strict';
const request = require('request');
// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = '<Subscription Key>';
// You must use the same location in your REST call as you used to get your
// subscription keys. For example, if you got your subscription keys from
// westus, replace "westcentralus" in the URL below with "westus".
const uriBase = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect';
const imageUrl =
'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg';
// Request parameters.
const params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
};
const options = {
uri: uriBase,
qs: params,
// body: '{"url": ' + '"' + imageUrl + '"}',
//body: stream,
body:imageAsBase64,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
答案 0 :(得分:1)
我尝试了一下,并使以下代码正常工作,您实际上非常接近实现它。最主要的是将Buffer对象传递给POST请求的body字段,并指定正确的content-type标头。
'use strict';
const request = require('request');
const fs = require("fs");
// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = <Subscription Key> ;
const uriBase = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect';
const imageBuffer = fs.readFileSync('image.jpg');
// Request parameters.
const params = {
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
};
const options = {
uri: uriBase,
qs: params,
body: imageBuffer,
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});