I understand Mongodb can store images in two ways.
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.
So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file `model. js` file and define the schema. The important point here is that our data type for the image is a Buffer which allows us to store our image as data in the form of arrays.
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()})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With