1

I'm implementing an application using C# in Visual Studio.I tried to retrieve data which are already in Mongodb.I retrieved some values but I don't know how to get an image which is in fs.files collection using GridFS.I need to display the retrieved image in a picture box of my application.

enter image description here

Here is the structure of fs.files collection in mongodb.

Can anyone please explain this?

Thank You

amavi
  • 11
  • 6
  • Is the "picture" stored as a byte array in mongodb? I've never used mongodb before, but however you retrieve it, you may just need to convert from a byte array to an image type in the c# code to be able to display it in your picture box. – Zack May 16 '16 at 16:54
  • Also, this question seems highly relevant from the sidebar http://stackoverflow.com/questions/4988436/mongodb-gridfs-with-c-how-to-store-files-such-as-images?rq=1 – Zack May 16 '16 at 16:55
  • Yap..Thanks..I already followed that way.But I was stuck on show the image in a picture box. Anyway I solved it..Thanks for your advice. – amavi May 17 '16 at 06:57
  • You can post your solution as an answer to your own question, and if other people find your question and answer and it helps them, they may upvote it. – Zack May 17 '16 at 13:49

1 Answers1

0

Here is my solution.

var fileName = @"D:CDAP\myfunction\ruwanwelimahaseya.jpg";//image which I want to save in the database var newFileName = @"D:CDAP\myfunction\new.jpg";

        using (var fs = new FileStream(fileName, FileMode.Open))
        {
            var gridFsInfo = DB.GridFS.Upload(fs, fileName);
            var fileId = gridFsInfo.Id;

            ObjectId oid = new ObjectId(fileId.ToString());
            var file = DB.GridFS.FindOne(Query.EQ("_id", oid));


            using (var stream = file.OpenRead())
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
                using (var newFs = new FileStream(newFileName, FileMode.Create))
                {
                    newFs.Write(bytes, 0, bytes.Length);
                    Image image = Image.FromStream(newFs);

                    f2.SizeMode = PictureBoxSizeMode.StretchImage;

                    f2.Image = image;

                }
            }
        }
amavi
  • 11
  • 6