5

I understand Mongodb can store images in two ways.

  1. in a regular document by storing the image as binary
  2. via Gridfs for managing larger images.

For simplicity and because the images I plan to server are small, I will go for option 1.

To serve the images to a browser I am using nodejs.

My question is how difficult will this be? How do you turn binary data to an actual image a browser will understand? What type of encoding is involved?

Could you point me to tutorials/examples elsewhere on the web?

By the way I know this may not be good idea for performance reasons, I plan to cache the images once served. I just want to avoid the file-system all-together.

4

2 回答 2

7

我强烈建议不要从 MongoDB 提供图像。

最好将它们存储在静态文件存储(S3)上,并可能将路径保留在 MongoDB 中。


您可能会使用 base64 编码将文件放入 mongodb:http ://www.greywyvern.com/code/php/binary2base64/ (或只是 base64 shell 实用程序)。

如果您只是使用常规文档,那么性能成本相对较低(只要缓存良好)。如果您使用的是混合数据库,其中有 GridFS 和常规文档,您的服务器上将需要大量 RAM——GridFS 查询的运行方式与文档查询完全不同。

转换图像可能会像这样工作:

var base64Data = imagefile.replace(/^data:image\/png;base64,/,""),
var dataBuffer = new Buffer(base64Data, 'base64');

// below line won't actually work but it's something along the lines of what you want:

db.foo.insert({magic: 123, etc... img: dataBuffer.toString()})
于 2012-07-19T20:59:10.713 回答
2

要让 Web 浏览器呈现内容,您需要做的就是发送正确的标头和响应正文。

因此,假设您正在尝试渲染 PNG 图像,您的 mimetype 将是image/png然后将图像文件字节添加到响应正文中。

然后浏览器会将此响应解释为 PNG 类型的图像并适当地呈现它

于 2013-10-15T08:30:53.460 回答