Monday, September 22, 2008

Convert image to byte to save in SQL database: C#

Here is a code for saving an image to SQL database.

First you need to save your image in MemoryStream. Include the namespace System.IO
Create an instance of MemoryStream.

MemoryStream stream = new MemoryStream();

Then save your image in the stream.

pic.Save(stream, System.Drawing.Image.ImageFormat.Jpeg);

Lastly, assign the stream to bytes.

bytes[] by = stream.ToArray();

The by is now readily available for saving in the database. If you have a column in your data table, the datatype is image, then you can assign by to this column.

No comments: