Pages

11/21/2010

Image Store Save/Retrieve C# Web SQL Server using Handler/ Generic Handler

This tutorial is to guide you to save/retrieve image using C# in ASP.Net Web

The saving image process is same as the windows form saving image process. You can get detail on my other tutorial which i wrote earlier which guide you to save/retrieve image in Windows Forms. You can read that tutorial from Click Here

For you ease i will copy past the code to show you how you save image in SQL server using C#.

1. First of all we need a database in SQL Server which contains a table with only two columns one is 'id' of type 'int' and second is of 'image' of type 'image'.

2. Open SQL Server 2005 Express Management Studio and create new database. Name it according to your choice.

3. After successfully creating database create a table with two columns described in step 1.

4. Now Open Visual Studio 2008/2010.

5. Create a project of windows Web.

6.. In this event function of button you are using to save the image, create an object of FileStream, a string and byte array. Or you can simply paste the code below.


FileStream fs;
string path = "C:\\Sunset.jpg";
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
//a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();

7. Now below this create database connectivity and store this byte array(picbyte) to the image column in the database table you created in starting steps. OR you can use this code.

string cString = "Initial Catalog=DB NAME;Data Source=SQL SERVER INSTANCE;User ID=DB USER;Password=DB USER PASSWORD;";
SqlConnection connection = new SqlConnection(cString);
string query = "insert into TableName (ColumnName) values (@pic)";
connection.Open();
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.Add(picparameter);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Image Saved");
connection.Close();

8. Now the image is saved in the database. You can see this by using query analyzer. Confirm it by the length of image column you will see when you will query it.

9. Now the image is successfully saved, its time to Retrieve it.

10. Retrieving and showing image in web is slightly different from windows form.

11. You need handler to show image.

12. You can add handler from right clicking the web project and adding new item.

13. Handler got the extension of .ashx. E.g. when you added handler from adding new item you get Handler.ashx. You can rename it to whatever you want.

14. Now you need a image control in the web page to show the image. You can use asp:image and in its ImageUrl attribute write handler's URl like

ImageUrl="~/Handler.ashx"

15. '~' sign is to get the project starting location. If its in any folder then write its name first after ~ sign.

16. In handler.ashx you will retrieve the image and show it. You can send the image id or user id to the handler if you want to show image at runtime depending on the user. Basically used in dynamic sites. You can send id like this

ImageUrl="~/Handler.ashx?id=1"

17. Handler code looks like

public void ProcessRequest (HttpContext context)
{
try
{
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
context.Response.ContentType = "image/jpg";
conDB = new System.Data.SqlClient.SqlConnection("Data Source=SERVER Name;Initial Catalog=DB Name;Integrated Security=True;");
conDB.Open();
int id = 'id of the user or image You can get it from URL also if you send it to handler by REQUEST';
string str = "Select (Image) from TableName where UserID or ImageID =" + id;
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(str, conDB);
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
byte[] img = (byte[])reader["Image"];
reader.Close();
memoryStream.Write(img, 0, img.Length);
context.Response.Buffer = true;
context.Response.BinaryWrite(img);
memoryStream.Dispose();
conDB.Close();
context.Response.OutputStream.Write(img, 0, img.Length);
context.Response.BinaryWrite(img);
}
catch (Exception ex)
{
context.Response.Redirect("Error.aspx");
}
}

18. Now the Image will be shown in the asp:image after retrieval from Database.

19. One handler is enough to show as many images you want to show in the web site.

Queries are welcomed........


Twitter Delicious Facebook Digg Favorites More