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.

jamjam
  • 3,171
  • 7
  • 34
  • 39

2 Answers2

7

I would strongly advise against serving images from MongoDB.

It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.


You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).

If you're just using regular documents then the performance cost is relatively low (so long as caching is good). If you're using a mixed database where you have GridFS and regular documents you're going to need a lot of RAM on your server(s) -- the GridFS queries will run completely differently from the document queries.

Converting the image might work like this:

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()})
Randall Hunt
  • 12,132
  • 6
  • 32
  • 42
  • That's very helpful. Now I have an idea how to store the images. Could you please expand your answer to include how I may serve the images? – jamjam Jul 19 '12 at 22:01
  • I mean it would depend on how you queried them? `var c = db.foo.find({imgname: "something"}; console.log(c.img)` It's your server so... I'm not entirely sure how to tell you serve stuff -- I assume you're using node? – Randall Hunt Jul 19 '12 at 23:15
  • The query is not the problem, I can get the data out. But what do I do with this binary data to make a web browser render it as a normal image? – jamjam Jul 19 '12 at 23:32
2

All you need to do to have your web-browser render the content is send the correct headers and response body.

So, assuming you are trying to render a PNG image, your mimetype would be image/png and then add the image files bytes to the response body.

The browser will then interpret this response as being an image of type PNG and render it appropriately

Matt Keeble
  • 244
  • 3
  • 8