Search code examples
c#asp.netsqlrepeaterashx

Get images from Database into ASHX file and Display into repeater


I want to Display images into repeater control from Database with the help of ASHX file. I am beginner to ASP.net. It would be really helpful if you can provide me any code example.

EDIT, from comments

I am trying to get images from database into repeater control.

This is what I did in aspx.cs file

cnn.Open(); 
SqlDataAdapter da1 = new SqlDataAdapter("select * from carousel", cnn);
DataTable dt1 = new DataTable(); da1.Fill(dt1);
Rp1.DataSource = dt1;
Rp1.DataBind();

this is my Repaeter

<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ID")%>'/> 

But I am Getting src="system.Byte" in results.

I know This is because the value coming from the database is a byte array representing the actual data of the image. So I want to know about ASHX


Solution

  • The question that I mentioned in the comments has some good examples on how you might go about putting the image on your site. This is the question I'm referencing.

    In particular, this answer shows a really good example of the method you'll need to employ.

    Basically, because you're getting the image as an array of bytes from the database (as in, the actual image it self, not a reference to the image), you'll need to use a slightly different method than an <asp:Image/> tag using the ImgUrl attribute.

    In summation, you'll do something like this (reference from the other answer):

    Create a regular HTML img element like so:

    <img runat="server" id="image"  />
    

    And in code behind do this:

    image.src="data:image/png;base64,"+Convert.ToBase64String(imageBytes);
    

    Where imageBytes is a byte[]