使用Linq从数据库检索图像到SQL [英] Retrieving an image from database with Linq to SQL
问题描述
在数据库中,我以图像"数据类型存储了图像,并显示为二进制代码. 现在,我想从一列中检索所有图像,并使用C#在asp.net页面上显示它们.
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;
然后我用这个:
foreach (Picture p in images)
{
galleryImages.Controls.Add(p);
}
但这不起作用,因为二进制文件无法转换为图片.我已经对此进行了Google搜索,发现我必须转换为Byte,然后再转换为图像?我找不到有关如何执行此操作的示例.
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.
推荐答案
这应该做到:
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);
}
请注意,Image.FromStream
拥有流的所有权-无论如何,它只是一个MemoryStream
,但出于各种原因,请确保处置该图像.
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.
嗯...我还没有意识到这是针对ASP.NET的.这使事情变得更加艰难-因为HTML将包含URL,然后您将需要稍后才能获取数据.
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.
图片是否具有某种ID?如果是这样,则获取该数据而不是实际数据,然后设置一个URL,该URL可以根据ID提供任何缩略图(通过从数据库中获取缩略图并仅使用适当的内容类型对其进行提供).
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).
这篇关于使用Linq从数据库检索图像到SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!