2012-01-11 39 views
1

我有一些圖像(主要是png和jpg),我將它們存儲在SQL Server 2008的FileStream中。我能夠檢索所述圖像並將它們存儲在MemoryStream中。如何在MemoryStream中顯示圖像?

我有一個特定的網頁,我需要在MemoryStream內顯示圖像。有什麼方法可以在HTML圖像標記中顯示MemoryStream的內容(或者更好,在ASP.NET Image控件中)?

+0

相信這是http://stackoverflow.com/questions/46788/how-to-bind-a-memorystream-to-aspimage-control – Jagd 2012-01-11 16:38:45

回答

10

是,

  1. 點處的圖像源到ASHX處理程序
  2. 有處理程序從數據庫中查詢圖像
  3. 寫字節響應流和設置內容類型

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

複製感謝您的幫助! – Jagd 2012-01-11 16:41:15

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 
}