如何在MemoryStream中显示图像?

时间:2012-01-11 16:13:06

标签: c# asp.net image memorystream

我有一些图像(主要是png和jpg),我存储在SQL Server 2008的FileStream中。我能够检索所述图像并将它们存储在MemoryStream中。

我有一个网页,我需要在MemoryStream中显示图像。我是否可以通过某种方式在HTML图像标记内显示MemoryStream的内容(甚至更好,在ASP.NET图像控件中)?

2 个答案:

答案 0 :(得分:10)

是的,

  1. 将图像源指向ashx处理程序
  2. 让处理程序查询数据库中的图像
  3. 将字节写入响应流并设置内容类型
  4. HTML

    <img src="loadimage.ashx?id=..."/>
    

    为项目和loadimage添加通用处理程序 处理

    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; } }
    }
    

答案 1 :(得分:1)

我使用以下代码从远程URL获取图像 - MemoryStream - 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
}