Tuesday, February 23, 2010

Insert Image File Into SqlServer Database using asp.net and c#

Save An Image Into SQL Server 2005 Database





Normally, images are saved in the web server folder, not in the database; this is for larger file size category. In some cases like, in bank, for example, they scan the user signatures as image files and save that file into the database.


Controls used in this application
◦System.Web.UI.HtmlControls.HtmlInputFile
◦System.Web.UI.WebControls.TextBox
◦System.Web.UI.WebControls.Button
Namespaces used in this application:
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.IO;
using System.Drawing.Imaging;


Solution with Code
Use the HtmlInputFile class, which you can declare an instance of with an tag. The following example is a complete ASPX file that lets a user upload an image file and a comment describing the image. The OnUpload method writes the image and the comment to a table named Pictures in a SQL Server database.


public void OnUpload(Object sender, EventArgs e)
{

int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new SqlConnection("Data Source=home;Initial Catalog=Image;Integrated Security=True");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image " + "(Image, Text) values (@pic, @text)", connection);
cmd.Parameters.Add ("@pic", pic);
cmd.Parameters.Add ("@text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}

}

The above created function is called using the onClick property of a button.

How do I read an image from a database and display it in a Web page
?

Here, I used the web page to display the image and not any other control. The following is the code for displaying the image from the database.


protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
MemoryStream stream = new MemoryStream ();
SqlConnection connection = new SqlConnection("Data Source=home;Initial Catalog=Image;Integrated Security=True");
try
{
connection.Open ();
SqlCommand command = new SqlCommand ("select Image from Image", connection);
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);
}
finally
{
connection.Close ();
stream.Close ();
}
}

No comments:

Post a Comment