0

How to show a image in database in the image control of Asp.net? We have to show the image of employee along with his details in the asp.net page, but the issue is how to show the image on the asp.net image control for the image control takes picture by the property ImageUrl.

Kindly guide....

HotTester
  • 5,620
  • 15
  • 63
  • 97

2 Answers2

5

You can create an HttpHandler(ashx) page which would take a querystring and set that as the imageUrl property of the image control

<asp:image id="imgEmployee" imageUrl="DisplayImage.ashx?employeeId=<someId>"/>

Now in DisplayImage.ashx, you can override the Processrequest like below:-

    public void ProcessRequest (HttpContext context) 
    { 
          int employeeId;
          if (context.Request.QueryString["employeeId"] != null)
   employeeId = Convert.ToInt32(context.Request.QueryString["employeeId"]);
          else
            throw new ArgumentException("No parameter specified");

        byte[] imageData= ;// get the image data from the database using the employeeId Querystring
        Response.ContentType = "image/jpeg"; // You can retrieve this also from the database
        Response.BinaryWrite(imageData);

    } 

Web.config changes:-

<httpHandlers>
  <add verb="*" path="img/*" type="DisplayImage"/>
</httpHandlers>

Details here and here.

Hope this helps..

Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
  • I think you got the question wrong. I have to show the image in the image control of asp.net not just on the web-page. – HotTester Mar 20 '10 at 08:17
  • @HotTester, the above code/concept would display the image in the IMG control. To explain more, suppose you have a page (EmployeeDetails.aspx) where you have the image control, the imageUrl of which is "DisplayImage.ashx?employeeId=12". When you request for "EmployeeDetails.aspx" page and when the image control is getting rendered, a request will go to the DisplayImage.ashx (an HttpHandler) which is just going to output the binary data for the image and then that would get displayed in the Image control of the Employee.aspx. Let me know If I still misunderstood your question. – Ashish Gupta Mar 20 '10 at 08:44
0

This can also be done without creating a handler.

//get the image from the database as byte array
byte[] image = (byte[])dr["image"];

//set the ImageUrl of the Image Control as a Base64 string
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image)

Or if you want the with and height also, create an Image by using a MemoryStream and get the image properties.

using (MemoryStream ms = new MemoryStream(image))
{
    System.Drawing.Image imageFromDB = System.Drawing.Image.FromStream(ms);

    Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
    Image1.Width = imageFromDB.Width;
    Image1.Height = imageFromDB.Height;
}
VDWWD
  • 35,079
  • 22
  • 62
  • 79