Images from DB in ASP.NET

Here is sample coding for displaying image from DB(byte[] in DB).

public SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings(connectionstring);
public SqlCommand command;

protected void Button1_Click(object sender, EventArgs e)
{
command = new SqlCommand("select img_data from [tbl_image] where img_Id=1", connection);
connection.Open();
byte[] imgData= (byte[])this.command.ExecuteScalar();
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(imgData, 0, imgData.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(memoryStream);
Response.ContentType = "image/Jpeg";
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
connection.Close();
}

...S.VinothkumaR.

No comments: