views:

1037

answers:

1

In my database I have stored images in the "image" data type, showing up as a binary code. I now want to retrieve all images from one column and diplay them on a asp.net page with C#.

databaseDataContext db = new databaseDataContext();

    var images = from Picture p in db.Pictures
                 select p.pictureThumb;

then I use this:

    foreach (Picture p in images)
    {
        galleryImages.Controls.Add(p);
    }

But that doesn't work because Binary can't be converted to Picture. I have Googled this and found that I have to cast to Byte and then to image? I can't find examples on how to do that though.

+5  A: 

This should do it:

databaseDataContext db = new databaseDataContext();

var images = from p in db.Pictures
             select Image.FromStream(new MemoryStream(p.pictureThumb.ToArray());
foreach (Image image in images)
{
    galleryImages.Controls.Add(image);
}

Note that Image.FromStream takes ownership of the stream - it's only a MemoryStream anyway, but do make sure that you dispose of the image, for various reasons.


EDIT: Ah... I hadn't realised that this was for ASP.NET. That makes things harder - because the HTML is going to contain URLs, and then you'll need to be able to fetch the data later.

Does a picture have an ID of some kind? If so, fetch that instead of the actual data, and then set up a URL which is able to serve any thumbnail based on the ID (by fetching it from the database and just serving it with an appropriate content type).

Jon Skeet
Thanks, that took care of a lot of problems. I have some issues with the loop though, "The best overloaded method match [...] has some invalid arguments". galleryImages refers to a PlaceHolder, but the other possibilities (Literal, Image, etc) give the same error. PLUS the Add(image) tells me "cannot convert from 'System.Drawing.Image' to 'System.Web.UI.Control'". I bet it's fairly obvious I'm very inexperienced with .NET :o
Skunk
That did it :) Retrieve the pictureID from the database, then use getImage.aspx.cs to extract the actual imagedata. Use ContentType = "image/jpeg"; and BinaryWrite.Thanks Jon!
Skunk
Cool - for someone who claims to be "very inexperienced" that was a really quick turnaround :)
Jon Skeet
I recognized a lot of things I already read on my Googlequest and realized how to use them :)
Skunk