Brent Oliver
Brent Oliver

Reputation: 171

asp.net display image from sqlreader

How can I get an image control on webpage to display from sqlreader?

I have an sqlreader with the binary data and content type fields, but don't know how to get it to display to the image control on my page.

found the "GetStream" method, but can't figure out the syntax for what I need.

Fields from sqlreader are: Image1, for binary Data Image1Content, for content type (image/jpg) Image1Name, for Image Name

Image control on page is "Image1"

I am assigning other controls on the page behind and would like to do the same with the image control/s.

Tried this, but get an error in the reader["Image1"] at the end:

 while (reader.Read())
                Image1.ImageUrl = reader.GetStream("data:image/jpg;base64," + Convert.ToBase64String((byte[])reader.["Image1"]));

Upvotes: 0

Views: 1524

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

It always helps to do things in multiple steps so you can see more clearly where things are going wrong. You don't need both GetStream() and reader["Image1"], they accomplish almost the same thing. I will demonstrate the latter since I do not know what index Image1 is at:

while (reader.Read())
{
    byte[] imgBytes = (byte[])reader["Image1"];
    string encodedBytes = Convert.ToBase64String(imgBytes);
    string url = string.Concat("data:image/jpg;base64,", encodedBytes);
    Image1.ImageUrl = url;
}

However, if you have more that one row, you will overwrite the image url on each iteration of Read(). I doubt that is what you intend to do but I can't really tell. I suspect you just want to call Read() once, not in a while loop, but if there is only one row you would not notice the difference.

Upvotes: 1

Related Questions