This blog is subject the DISCLAIMER below.

Sunday, April 27, 2008

How to save image in SQL Server database?

Q: How to save image in SQL Server database?

A: It's the most common question asked in technical forums, the answer is so simply is to convert your image to binary and save the equivalent binary data to the database.

I am expecting you know how to Insert\get data to\from SQL Server.

To convert image to binary you need to write this piece of code

   1: System.IO.FileStream fs = new System.IO.FileStream(@"ImagePath", System.IO.FileMode.Open);
   2:             byte[] imageAsBytes = new byte[fs.Length];
   3:             fs.Read(imageAsBytes, 0, imageAsBytes.Length);
   4:             fs.Close();

You need a table with column of binary\image datatype to be able to insert the equivalent binary data of image.

And what about retrieving binary data to be converted to image

You just need to initiate new Image from MemoryStream object which takes array of bytes as an argument -Array of bytes comes from SQL Server-

1: Image img = Image.FromStream(new System.IO.MemoryStream(imageAsBytes));


Anonymous said...

gamed ya ramy walahy nice

bas so2l ya ramy howa mesh a7san low ana 3mlt save lel path bt3ha
y3ani 5ltha ta5od path el image fe el server mthili tab2a a5f??

Mohamed Gamal El-Den said...

@ Anonymous
What if two different people uploaded two different . Pics with the same Name ???

sh@dy said...

The issue claimed by Gamal can be solved by using a naming convention or just generating GUIDs for the image name, after all the image path will be saved in the DB so you don't care about its name.

Another issue that might be against saving file path rather saving it as binary, is that images on disk can be deleted by any one who has the permission to delete them from disk..

Also in case of using binary, your images will be backed up by default when u backup ur DB for eg.. while using file path will leave u the overhead of backing up ur images..

There's another solution for the whole issue on sqlserver2008.. There's a new type called "FILESTREAM" which is a bit of both solutions.. Actually it saves the files on Disk too as separate file from the DB files.. but the saving thing is done by Sqlserver.. so now the file content (not just the path) is a part of the DB.. yet you can get a handle/path for it to use it as an ordinary file..

Anonymous said...

nice ya shady thankssssssssss a lot

eu4 console commands said...

the size of my picture is 4MB when I save in table is too much in storage so is there any idea abut decompress or resize to make size smaller ..?? can you help me
I have problem ..every things was done by regarding your video but after inserting an record nothing save in DB why?

item id ark said...

I have a problem when i try to read the image from the stream "invalid parameter ms", and i couldn't find the error
Please answer my question sooner and thank u for the tutorial