Friday, September 3, 2010

How to SAVE and RETRIEVE image in DataBase SQL with LINQ

public void SaveImage()
{

byte[] pic = null;
int len = FUImage.PostedFile.ContentLength;
pic = new byte[len];
FUImage.PostedFile.InputStream.Read(pic, 0, len);

Table_Name tab_name = new Table_Name()
{
Image = pic,
};
_data.odatacontext.Table_Name.InsertOnSubmit(tab_registration);
_data.odatacontext.SubmitChanges();
}
}


public void RETRIEVEImage()
{

try
{
System.IO.MemoryStream stream = new MemoryStream();
SqlConnection connection = new
SqlConnection(@"Data Source=(local);Initial Catalog=DataBaseName;User ID=sa;Password=123");

connection.Open();
SqlCommand command = new
SqlCommand("select top(1) Image from Table_Name order by RID desc", connection);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
System.Drawing.Bitmap bitmap = new Bitmap(stream);
Response.ContentType = "image/gif";
bitmap.Save(Response.OutputStream, ImageFormat.Gif);
}
finally
{
connection.Close();

}
}