简体   繁体   English

使用Linq to SQL从数据库中检索图像

[英]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#. 我现在想要从一列中检索所有图像,并使用C#将它们显示在asp.net页面上。

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. 但这不起作用,因为Binary无法转换为Picture。 I have Googled this and found that I have to cast to Byte and then to image? 我用谷歌搜索了这个,发现我必须转向Byte然后成像? I can't find examples on how to do that though. 我找不到如何做到这一点的例子。

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. 请注意, Image.FromStream取得了流的所有权 - 无论如何它只是一个MemoryStream ,但确保您出于各种原因处理图像。


EDIT: Ah... I hadn't realised that this was for ASP.NET. 编辑:啊......我没有意识到这是针对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. 这会让事情变得更难 - 因为HTML将包含URL,然后您需要能够以后获取数据。

Does a picture have an ID of some kind? 图片是否有某种ID? 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). 如果是这样,请获取该数据而不是实际数据,然后设置一个能够根据ID提供任何缩略图的URL(通过从数据库中获取并仅使用适当的内容类型提供)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM