【问题标题】:How to display images in MemoryStream?如何在 MemoryStream 中显示图像?
【发布时间】:2012-05-22 05:17:08
【问题描述】:
我有一些图像(主要是 png 和 jpg)存储在 SQL Server 2008 的 FileStream 中。我能够检索所述图像并将它们存储在 MemoryStream 中。
我有某个网页需要在 MemoryStream 中显示图像。有什么方法可以让我在 HTML 图像标签中显示 MemoryStream 的内容(或者更好的是,在 ASP.NET 图像控件中)?
【问题讨论】:
标签:
c#
asp.net
image
memorystream
【解决方案1】:
是的,
- 将图像源指向 ashx 处理程序
- 让处理程序从数据库中查询图像
- 将字节写入响应流并设置内容类型
html
<img src="loadimage.ashx?id=..."/>
为您的项目添加通用处理程序并加载图像
处理程序
class loadimage: ihttphandler
{
public void Process(HttpContext context)
{
var id = context.Request["id"];
var row = GetImageFromDb(id);
var response = context.Response;
response.AddHeader("content-disposition", "attachment; filename=" + row["anem of image"]);
response.ContentType = row["mime type"].ToString(); //png or gif etc.
response.BinaryWrite((byte[])row["image blob"]);
}
public bool Reuse { get {return true; } }
}
【解决方案2】:
我正在使用以下代码从远程 URL 获取图像
- 记忆流
- System.Drawing.Image
// Set image url
string imgURL = ("http://cdn.flikr.com/images/products/" + imageName);
// Get image into memory
WebClient lWebClient = new WebClient();
byte[] lImageBytes = lWebClient.DownloadData(imgURL);
MemoryStream imgStream = new MemoryStream(lImageBytes);
image = System.Drawing.Image.FromStream(imgStream);
if (image.Width >= 200)
{
// do something
}