Storing images in your documentDB – MongoDB

MongoDB has special API called GridFS to manipulate the files. It stores the files as bit chunks with 256k. Then we can retrieve the bit sequence to a image again. Keep remember to create a separate namespace to store these image files. I have used a namespace called photo – GridFS gfsPhoto = new GridFS(db,”photo”);
Here is the Java code on how to store an image and retrieve it.
package com.technodyne.core;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class SaveImage {

	public static void main(String[]args){

		try {

			Mongo mongo = new Mongo("127.0.0.1",27017);
			DB db = mongo.getDB("imagedb");
			DBCollection collection = db.getCollection("dummyImageCollection");

			String newFileName = "technodyne-java-image";
			File imageFile = new File("C:UsersSUPUNDesktopimages.jpg");

			GridFS gfsPhoto = new GridFS(db,"photo");
			try {
				GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
				gfsFile.setFilename(newFileName);
				gfsFile.save();

				DBCursor cursor = gfsPhoto.getFileList();
				while(cursor.hasNext()){
					System.out.println(cursor.next());
				}

				GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
				imageForOutput.writeTo("C:UsersSUPUNDesktopjava-monngo-image.jpg");
			    gfsPhoto.remove(gfsPhoto.findOne(newFileName));

			    System.out.println("Done");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (UnknownHostException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		catch(MongoException e){
			e.printStackTrace();
		}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s