Vinayaka Karjigi
Vinayaka Karjigi

Reputation: 1090

Saving and retrieving of images from SQL Server database using c#

I have created a web page where I have used Image control to display the image. Along with this control I have some labels and input box also

Below is the code which I have used to save the image to database

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlParameter UploadedImage = new SqlParameter("@image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;

string sql = "insert into imageDB(Image) values (@image)";

using (SqlCommand cmd = new SqlCommand(sql, conn))
{
   cmd.Parameters.Add(UploadedImage);
   cmd.ExecuteNonQuery();
}

and below is the code I have used to retrieve the image from database

byte[] rawImg = (byte[])rdr["image"];
MemoryStream Stream = new MemoryStream();
Stream.Write(rawImg, 0, rawImg.Length);
Bitmap Display_Picture = new Bitmap(Stream);
//after this no idea how to proceed

I have read some links all are suggesting we can not set this byte information to Image control.

Let me know if my way of retrieving the image from data base is right, if its right, what type of control I should use, so that image which has been retrieved from database can be displayed on web page

Upvotes: 2

Views: 15025

Answers (3)

kiriloff
kiriloff

Reputation: 26333

To retrieve image, and show on asp.net Image control, you can

    cn.Open();
    SqlCommand cm = new SqlCommand("select * from ImageCollection where img_id='" + DropDownList1.SelectedItem.ToString() + "'", cn);
    SqlDataAdapter da = new SqlDataAdapter(cm);
    SqlDataReader dr = cm.ExecuteReader();
    try
    {
        if (dr.Read())
        {

            string image1 = Convert.ToString(DateTime.Now.ToFileTime());
            FileStream fs1 = new FileStream(image1, FileMode.CreateNew, FileAccess.Write);
            byte[] bimage1 = (byte[])dr["passport_photo"];
            fs1.Write(bimage1, 0, bimage1.Length - 1);
            fs1.Flush();
            Image1.ImageUrl = "~/images/"+DropDownList1.SelectedItem.ToString();
        }
        dr.Close();
        cn.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }

Alternative solution:

Implement a handler to serve the image. Have a look at the System.Web.IHttpHandler interface.

The idea would be to write an image tag in your page along the lines of:

<asp:image runat="server" imageurl="~/Image.ashx?ID=xxx" />

Then in your handler implementation, get the id from the querystring, retrieve the image as you're already doing and then write directly to the response stream.

Upvotes: 0

MUG4N
MUG4N

Reputation: 19717

Is my way of retrieving the image from database right?

I would use the following code instead (sorry not tested):

byte[] imageBytes = Convert.FromBase64String(rdr["image"]);
MemoryStream stream = new MemoryStream(imageBytes);
Image image = Image.FromStream(stream);

How do I bind the image to an asp.net image control?

I would create an HttpHandler which gets and returns the image. Then bind the ImageUrl property on the asp:Image to the url of the HttpHandler. How you can do this you can see in the answer of Dale Ragan over here: How to bind a MemoryStream to asp:image control?

Upvotes: 1

Martin Mulder
Martin Mulder

Reputation: 12934

First, in your example your have to reset the Position inside your stream to 0: Stream.Position = 0;

Second, you have to write your image to a local cache folder of your web service that is part of your web application. You image control can have a Source-reference (img.src) to the address of that image.

Or... you can create an AXD-file / HttpHandler. An AXD file is a file, just like an ASPX, but specialized in returning any type of data, like an image.

For more info, see: http://blog.kurtschindler.net/post/using-httphandlers-to-serve-image-files

Upvotes: 0

Related Questions