2010-08-23 69 views

回答

3

我會創建一個image元素,其中src屬性指向查詢字符串中帶有圖像ID的ashx處理程序。在此處理程序,你可以有以下代碼:

 string ImageId = Request.QueryString["img"]; 
     string sqlText = "SELECT img_data, img_contenttype FROM Images WHERE img_pk = " + ImageId; 

     using (var connection = new SqlConnection("your connection string")) 
     { 
      using (var command = new SqlCommand(sqlText, connection)) 
      { 
       connection.Open(); 
       using (SqlDataReader dr = command.ExecuteReader()) 
       { 
        if (dr.Read()) 
        { 
         Response.Clear(); 
         Response.ContentType = dr["img_contenttype"].ToString(); 
         Response.BinaryWrite((byte[]) dr["img_data"]); 
         Response.End(); 
        } 
       } 
      } 
     } 
2

你第一次得到Page.Response,然後調用BinaryWrite或使用流directly

另外,我對文件系統recommned存儲圖像,而不是DB。

2

在html頁面中,需要使用指向另一個頁面(或ashx處理程序)的src屬性呈現<img>標記。在那個其他頁面/處理程序只有你生成的輸出是圖像的二進制數據(可能還有一些http頭文件)。
使用參數指定圖像。

1

從數據庫中檢索,使用爲System.Drawing.Image類從二進制轉換成圖像,然後將圖像保存在臨時文件夾。給temp文件夾的路徑在HTML/ASCX/ASPX <img>標籤等

C#:

MemoryStream ms = new MemoryStream(binaryImage); 
Bitmap BMP = new Bitmap(ms); 
String path = Server.MapPath("..\\Temp"); 

if (!Directory.Exists(path)) 
{ 
    Directory.CreateDirectory(path); 
} 

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path); 

if (SecurityManager.IsGranted(writePermission)) 
{ 
    System.Drawing.Image img = new System.Drawing.Bitmap(ms); 
    img.Save(path + "\\xyz.jpg", ImageFormat.Jpeg); 
} 

HTML/ASPX:

<img src="Temp/xyz.jpg"> 
相關問題