Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving an image from database with Linq to SQL

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.

like image 609
Kablam Avatar asked Aug 12 '09 13:08

Kablam


1 Answers

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).

like image 108
Jon Skeet Avatar answered Oct 22 '22 15:10

Jon Skeet