如何将图像从 url 加载到 nodejs 的缓冲区中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18264346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to load an image from url into buffer in nodejs
提问by CodeMonkeyB
I am new to nodejs and am trying to set up a server where i get the exif information from an image. My images are on S3 so I want to be able to just pass in the s3 url as a parameter and grab the image from it.
我是 nodejs 的新手,正在尝试设置一个服务器,我可以从图像中获取 exif 信息。我的图像在 S3 上,所以我希望能够将 s3 url 作为参数传入并从中获取图像。
I am u using the ExifImage project below to get the exif info and according to their documentation:
我正在使用下面的 ExifImage 项目来获取 exif 信息并根据他们的文档:
"Instead of providing a filename of an image in your filesystem you can also pass a Buffer to ExifImage."
“您还可以将缓冲区传递给 ExifImage,而不是在文件系统中提供图像的文件名。”
How can I load an image to the buffer in node from a url so I can pass it to the ExifImage function
如何将图像从 url 加载到节点中的缓冲区,以便我可以将其传递给 ExifImage 函数
ExifImage Project: https://github.com/gomfunkel/node-exif
ExifImage 项目:https: //github.com/gomfunkel/node-exif
Thanks for your help!
谢谢你的帮助!
回答by Dan Kohn
Try setting up request like this:
尝试像这样设置请求:
var request = require('request').defaults({ encoding: null });
request.get(s3Url, function (err, res, body) {
//process exif here
});
Setting encodingto nullwill cause request to output a buffer instead of a string.
设置encoding为null将导致请求输出缓冲区而不是字符串。
回答by Yehonatan
I was able to solve this only after reading that encoding: nullis requiredand providing it as an parameter to request.
我可以只读取后,解决这个encoding: null是必需的,并提供其作为参数来请求。
This will download the image from url and produce a buffer with the image data.
这将从 url 下载图像并生成包含图像数据的缓冲区。
Using the request library -
使用请求库 -
const request = require('request');
let url = 'http://website.com/image.png';
request({ url, encoding: null }, (err, resp, buffer) => {
// Use the buffer
// buffer contains the image data
// typeof buffer === 'object'
});
Note: omitting the encoding: nullwill result in an unusable string and not in a buffer. Buffer.from won't work correctly too.
注意:省略encoding: null将导致无法使用的字符串,而不是在缓冲区中。Buffer.from 也不会正常工作。
This was tested with Node 8
这是用 Node 8 测试的
回答by Timothy Strimple
Use the requestlibrary.
使用请求库。
request('<s3imageurl>', function(err, response, buffer) {
// Do something
});
Also, node-image-headersmight be of interest to you. It sounds like it takes a stream, so it might not even have to download the full image from S3 in order to process the headers.
此外,您可能对node-image-headers感兴趣。听起来它需要一个流,因此它甚至可能不必从 S3 下载完整图像来处理标头。
Updated with correct callback signature.
更新了正确的回调签名。

