Как показать изображение на веб-странице, на которое пришёл ответ api (компьютерное зрение - сервис thumbnil в лазури) в узле js - PullRequest
1 голос
/ 24 июня 2019

Это ответ от 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 Ответ

1 голос
/ 25 июня 2019

Я попытался проверить решение в комментарии @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)

Результат приведенного выше кода какниже запустите на моем местном env.

enter image description here

Надеюсь, это поможет.

...