11

How to retrieve images from sql database in asp.net using c#.

i want to retrieve the image file from database and then display the image in a tag.

i try this code but it is not working

aspx

 <asp:Image ID="Image1" runat="server" ImageUrl="" Height="150px" Width="165px" />

code behind

 Byte[] bytes = (Byte[])ds.Tables[0].Rows[0]["image"];
 Response.Buffer = true;
 Response.Charset = "";
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = "image/jpg";
 Response.BinaryWrite(bytes);
 Response.Flush();
 Response.End();

How to give link to the ImageUrl="" of this image???

9
  • Define not working, what errors are you getting? Commented Feb 18, 2013 at 11:29
  • Oh and MIME is image/jpeg not image/jpg. Commented Feb 18, 2013 at 11:30
  • Is this a page or a generic handler (ashx)? Commented Feb 18, 2013 at 11:30
  • You also need Response.Clear() Commented Feb 18, 2013 at 11:39
  • 1
    @AhmadAbbasi That is a filename not a URI. However, if you are returning the image by addressing this http://domain/Student.aspx then your ImageUrl would be this: http://domain/Student.aspx. Commented Feb 18, 2013 at 12:02

3 Answers 3

17

Create a generic http handler as follows

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
          empno = Convert.ToInt32(context.Request.QueryString["id"]);
       else
          throw new ArgumentException("No parameter specified");

       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);

       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }       
       //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
         string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
         SqlConnection connection = new SqlConnection(conn);
         string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
         SqlCommand cmd = new SqlCommand(sql,connection);
         cmd.CommandType = CommandType.Text;
         cmd.Parameters.AddWithValue("@ID", empno);
         connection.Open();
         object img = cmd.ExecuteScalar();
         try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
       {
            connection.Close();
       }
    }

    public bool IsReusable
    {
        get
        {
             return false;
        }
    }


}

and display image as follow

 Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

There are some links below
Showing image in GridView from the database?
How to show a image in database in the image control of Asp.net?
Display image from database in ASP.net with C#
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129

Sign up to request clarification or add additional context in comments.

1 Comment

I'd be interested on your opinion on whether to set IsReusable to true or false and why?
3

I don't think this is the right approach. You should not embed image into html, and this is not the right way anyway.

I suggest adding an ashx (generic handler) and use it to generate the image from query string, then ini the page use something like

<asp:Image ImageUrl='GetImage.ashx?id=12345' ... />

Comments

0

With Entity Frame work

With SQL (Code Project)

<asp:Image ID="ImgProfilePic" runat="server"  />

    byte[] imagem = (byte[])(dr["IMG"]);
string PROFILE_PIC = Convert.ToBase64String(imagem);
ImgProfilePic.ImageUrl = String.Format("data:image/jpg;base64,{0}", PROFILE_PIC);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.