使用Node.js的api

spStacker

我正在使用节点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);
});
特里·伦诺克斯

我尝试了一下,并使以下代码正常工作,您实际上离将其付诸实践非常近。最主要的是将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);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章