问题
I am using azure face api using node js, below is the code. However instead of the image hosted some where i want to use my local image and post it. i tried different options but it is not recognizing the image format or invalid image url
below are the things i have tried
1) var stream = fs.createReadStream('local image url');
2) var imageAsBase64 = fs.readFileSync('image.jpg','base64');
below is the code
'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);
});
回答1:
I played around with this and got the following code working, you were actually super-close to getting it going. The main thing is to pass the Buffer object to the body field of the POST request, and specifying the correct content-type header.
'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);
});
来源:https://stackoverflow.com/questions/54574681/face-api-with-nodejs