如何在Node.js中请求图像和输出图像 [英] How to request images and output image in Node.js

查看:21
本文介绍了如何在Node.js中请求图像和输出图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试获取图像并显示在url上.并且我使用请求模块.

I try to get the image and display on a url. and I use request module.

例如,我要获取图像 https://www.google.com/images/srpr/logo11w.png ,并在我的网址上显示 http://example.com/google/logo .

For example, I want to get the image https://www.google.com/images/srpr/logo11w.png, and display on my url http://example.com/google/logo.

或通过< img src ="http://example.com/google/logo"/> 显示.

然后我尝试使用请求表达:

app.get("/google/logo", function(req, res) {
  request.get("https://www.google.com/images/srpr/logo11w.png", 
        function(err, result, body) {
    res.writeHead(200, {"Content-Type": "image/png"});
    res.write(body);
    res.end();
  })
})

,但响应不是图像.如何获取图像并输出?

but the response is not a image. How to get image and output?

请给我一些有关该问题的建议.谢谢.

Please give me some suggestion about the question. THANKS.

推荐答案

在发出请求时尝试指定 encoding:null ,以使响应主体为您认为的 Buffer 可以直接写入响应流:

Try specifying encoding: null when making the request so that the response body is a Buffer that you can directly write to the response stream:

app.get("/google/logo", function(req, res) {
    var requestSettings = {
        url: 'https://www.google.com/images/srpr/logo11w.png',
        method: 'GET',
        encoding: null
    };

    request(requestSettings, function(error, response, body) {
        res.set('Content-Type', 'image/png');
        res.send(body);
    });
});

另一方面,如果您未指定 encoding:null ,则 body 参数将是String而不是Buffer.

On the other hand if you do not specify encoding: null, the body parameter will be a String instead of a Buffer.

这篇关于如何在Node.js中请求图像和输出图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆