【问题标题】:How to show image in web page which came response of api ( computer vision - thumbnil service in azure ) in node js如何在节点js中显示来自api(计算机视觉 - azure中的缩略图服务)响应的网页中的图像
【发布时间】:2019-11-06 04:19:29
【问题描述】:

这是来自 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
    }
};

【问题讨论】:

  • 您可以将响应字节转换为base64,并在包含图像数据的HTML页面中返回一个图像标签,如here所示。
  • 它不工作
  • @AbhiSavadiya 你的问题描述的太简单了,不知道怎么帮到你。您能否发布有关您的标题的更多详细信息,并在 NodeJS 中发布一些必要的代码?请参考 SO 帮助主题 stackoverflow.com/help/how-to-ask 更新您的帖子。谢谢。
  • @peterpan 现在看看可以吗?

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


【解决方案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)

上面代码的结果如下在我的本地环境上运行。

希望对你有帮助。

【讨论】:

  • 能否解释一下这行代码 request.post(options).pipe(res)
  • @AbhiSavadiya 请参考npmjs.com/package/request#streaming。只需管道写入认知api的请求响应流来表达响应。
  • Thakyou @peterpan
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 2015-03-27
  • 1970-01-01
  • 2017-07-15
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多