2012-10-11 16 views
0

當前我使用GenericHandler(.ashx)在圖像控件中顯示圖像。以generichandler(.ashx)設置的字節數組檢索圖像控件的圖像?

請參見下面的代碼:

[1] .ASPX 
    <asp:Image ID="Image1" runat="server" Width="350px" Height="415px" /> 
[2] .cs(codebehind) 
    Image1.ImageUrl = string.Format("GridviewImage.ashx?ItemID={0}", itemID); 

現在我需要的Image1圖像作爲字節數組(byte[])。

可能嗎?

+2

我問過類似的問題在這裏(包括代碼): http://stackoverflow.com/questions/1507572/streaming-databased-images-using-httphandler – IrishChieftain

+0

謝謝你的建議.... ....我見過'公共布爾IsReusable { 得到 { return true; } }'....但我不知道如何使用它請張貼代碼片段作爲答案非常感謝你 – Pritesh

+0

你是如何使用處理程序?我看到的只是ASPX中的靜態圖像,我不確定你的問題是什麼?我發佈了一個代碼片段,它使用一個處理程序將圖像放入GridView中,希望這會有所幫助。 – IrishChieftain

回答

1

如果您有多個圖像流式傳輸到頁面,請將IsReusable設置爲true。使用DataReader將圖像傳回,而不是像其他鏈接那樣的DataSet。

<img src='ImageHandler.ashx?ProductID=<%# Eval("ProductID")%>' alt="<%# Eval("ProductName") %>" 
    title="<%# Eval("ProductName") %>" /> 

    public class ImageHandler : IHttpHandler 
    { 
     public void ProcessRequest(HttpContext context) 
     { 
      if (context.Request.QueryString["productID"] != null) 
      { 
       try 
       { 
        string ProductID = context.Request.QueryString["ProductID"]; 
        if (Convert.ToInt32(ProductID) > 0) 
        { 
#if DEBUG 
     const string CONN = "Initial Catalog=db1;Data Source=server1;Integrated Security=SSPI;"; 
#else 
     const string CONN = "server=server2;database=db2;uid=un2;pwd=pw2;"; 
#endif 
         string selectQuery = "SELECT Photo FROM dbo.Products WHERE dbo.Products.ProductID=" + ProductID.ToString(); 
         SqlConnection conn = new SqlConnection(CONN); 
         SqlCommand cmd = new SqlCommand(selectQuery, conn); 

         conn.Open(); 
         SqlDataReader dr = cmd.ExecuteReader(); 

         dr.Read(); 
         context.Response.BinaryWrite((Byte[])dr[0]); 
         dr.Close(); 
         conn.Dispose(); 
         // context.Response.End(); --> caused an "Abort thread" error - this is correct and is a special exception 
        } 
       } 
       catch (Exception ex) 
       { 
        ErrorReporting.LogError(ex); 
       } 
      } 
      else 
       throw new ArgumentException("No ProductID parameter specified"); 
     } 

     public bool IsReusable 
     { 
      get 
      { 
       return true; 
      } 
     } 
    } 
+0

抱歉,如果這是愚蠢的問題,因爲我是新手到asp.net ...這裏'context.Response.BinaryWrite((Byte [])dr [0]);'是在'ImageHandler'我怎麼能從我的代碼隱藏(.cs)文件...非常感謝您的回答 – Pritesh

+0

此代碼是一個類,而不是您的代碼隱藏。頂部的img標籤位於您的ASPX表單中,並對處理程序類進行內聯調用。 – IrishChieftain

+0

確定還有一個問題...'ImageHandler'將在'.aspx'頁面的'Image'控件中設置圖像。之後,如果我想獲得'圖像的字節數組(字節[])'現在''圖像'控制'.aspx'頁.....非常感謝你 – Pritesh