如何在节点js中的api(计算机视觉-天蓝色的thumbnil服务)响应后的网页中显示图像

时间:2019-06-24 11:03:10

标签: node.js image azure api azure-cognitive-services

这是来自api的响应

apim-request-id: a6ac620f-8484-4bdf-a9ed-d26080186769
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Mon, 24 Jun 2019 09:10:23 GMT
Content-Length: 49368
Content-Type: image/jpeg

在这里,调用api的代码

const express = require("express");
const app = express();
const http = require("http").Server(app).listen(8080);
const fs=require("fs");
const request = require('request');

// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = 'key';

const uriBase =
    'https://centralindia.api.cognitive.microsoft.com/vision/v2.0/generateThumbnail';

const imageUrl =
    'https://smworld.co.in/images/bg1.jpg';

// Request parameters.
const params = {
    'width': '300',
    'height': '300',
    'smartCropping': 'true'
};

const options = {
    uri: uriBase,
    qs: params,
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

1 个答案:

答案 0 :(得分:1)

我尝试在@Wiktor Zychla注释中测试该解决方案,但它仅适用于png图像,不适用于jpeg。因此,我尝试提供解决方案以将图像url嵌入到静态html内容中。

这是我的示例代码供您参考。

var request = require('request');

const subscriptionKey = 'key';

const uriBase = 'https://centralindia.api.cognitive.microsoft.com/vision/v2.0/generateThumbnail';

const imageUrl = 'https://smworld.co.in/images/bg1.jpg';

// Request parameters.
const params = {
    'width': '300',
    'height': '300',
    'smartCropping': 'true'
};

const options = {
    uri: uriBase,
    qs: params,
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

const express = require('express')
const app = express()

app.get('/img', function(req, res) {
    request.post(options).pipe(res)
})

// embed an image url `/img` into the html code
app.get('/', function (req, res) {
        var html = '<h2>Hello world</h2></br><img src="/img"/>'
        res.send(html)

})

app.listen(3000)

以下代码的结果在我的本地环境中运行。

enter image description here

希望有帮助。