Previous | Home | Next |
How to Save Image in Database
Create a table in a SQL Server 2005 database which has at least one field of type IMAGE.

Design

- using System.Data.SqlClient;
- using System.Drawing;
- using System.Data;
- using System.IO;
- using System.Drawing.Imaging;
Source Code for Save the image file into the database
protected void Button1_Click(object sender, EventArgs e) { int length = FileUpload1.PostedFile.ContentLength; byte[] pic = new byte[length]; FileUpload1.PostedFile.InputStream.Read(pic, 0, length); // Insert the image and comment into the database SqlConnection con = new SqlConnection(@"data source=R4R-01 \SQLEXPRESS;initial catalog=saveimage;integrated security=true"); try { con.Open(); SqlCommand cmd = new SqlCommand("insert into saveimage1 " + "(Picture, Comment) values (@a, @b)", con); cmd.Parameters.Add("@a", pic); cmd.Parameters.Add("@b", TextBox1.Text); cmd.ExecuteNonQuery(); } finally { con.Close(); } }
Read image from a database using ADO.NET and display it in a Web Page.
protected void Button2_Click(object sender, EventArgs e) { // Put user code to initialize the page here MemoryStream stream = new MemoryStream(); SqlConnection con = new SqlConnection(@"data source=R4R-01\SQLEXPRESS;initial catalog=saveimage;integrated security=true"); con.Open(); SqlCommand command = new SqlCommand("select picture from saveimage1",con); byte[] image = (byte[])command.ExecuteScalar(); stream.Write(image, 0, image.Length); Bitmap bitmap = new Bitmap(stream); Response.ContentType = "image/gif"; bitmap.Save(Response.OutputStream, ImageFormat.Gif); }
Output:

Previous | Home | Next |