About Me

My photo
I'm a C# developer and that takes up most of my time but when I'm not in front of the computer, I do a lot of mountain biking, skiing and spending time with my dog. When I'm not doing any of that stuff, I'm spending time with my lovely wife.

Friday, September 19, 2008

On Working with Database Images

Last night I ended up having to work with saving and retrieving images from a database and I have found that it's actually very simple to do.

First thing to note - the datatype to used to load and save an image is a byte[].

The next thing you should know is that you cannot run an update or delete statement on an image column without passing the image to the query using a parameter.

To load an image, fill a datatable as you normally would.
byte[] imgBytes = (byte[])sqlCommand.ExecuteScalar("Select pic from picTable where pic_id=1",connection);
I found most of this code here. Create an System.Drawing.Image object from the resulting byte[].
System.Drawing.Image myImage;
System.IO.MemoryStream ms = new System.IO.MemoryStream;

// writing the image bytes to the memorystream.
ms.write(imgBytes,0,imgBytes.Length);

// creating the image from the memorystream.
myImage = Image.FromStream(ms,true);
ms.Close();
You can fill a picturebox or whatever with your shiny new image.

The other half of this equation is getting those images saved back to the database which means converting from an image back to a byte[].
System.IO.MemoryStream ms = new MemoryStream();
// use whatever format you need to here
myCurrentImage.Save(ms, ImageFormat.Jpeg);

// convert the bytes in the memorystream to a byte[]
byte[] imageArray = ms.ToArray();
To insert this byte[] into your image column, you'll need to create an SqlParameter object and use that in an SqlCommand object.
Using System.Data.SqlClient;
SqlCommand cmd = new SqlCommand("INSERT INTO pic values (@image)"),mySqlConnection);
SqlParameter param = new SqlParameter("@image", SqlDbType.Image);
param.Value = imageArray;(from above)
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
The image should now be saved into your database.

So that's how you deal with images in a database. I hope this helps anyone that is having problems with this issue.

No comments: