2011-11-25 48 views
0

可能重複:
What's the best way to display an image from a sql server database in asp.net?
bytearray to image asp.net如何使用c#在asp.net中顯示來自Sql Server 2008的圖像?

你怎麼能使用C#在asp.net中顯示從SQL Server 2008的圖像?

這是我到目前爲止在我的代碼隱藏。然後我想獲取圖像並將其顯示在我的.net頁面的桌面上。 (將圖像.png類型的,並且作爲VarBinary存儲)

HANDLER

using System; 
using System.Web; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Data; 
using System.Data.SqlClient; 
using System.Web.Caching; 
using System.Configuration; 
using System.Web.Configuration; 
using System.IO; 


namespace RocoSportsWA 
{ 
    public class DisplayImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
    { 
     private SqlConnection _connection; 
     private SqlCommand _command; 
     private HttpContext _context; 

     public void ProcessRequest(HttpContext context) 
     { 

     } 

     public bool IsReusable 
     { 
      get 
      { 
       return true; 
      } 
     } 

     public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object state) 
     { 
      // Get the employee ID from the query string 
      string _logo = context.Request["Logo"]; 
      if (String.IsNullOrEmpty(_logo)) 
       return null; 

      int logo = 0; 
      bool ok = int.TryParse(_logo, out logo); 
      if (!ok) return null; 

      _context = context; 
      string conn = WebConfigurationManager.ConnectionStrings["Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"].ConnectionString; 
      // Select the image from the database 
      _connection = new SqlConnection(conn); 
      _connection.Open(); 
      _command = new SqlCommand("SELECT Logo from TEAM where Team = @HomeTeam, _connection"); 
      _command.Parameters.AddWithValue("@HomeTeam", logo); 
      return _command.BeginExecuteReader(cb, state); 
     } 

     public void EndProcessRequest(IAsyncResult ar) 
     { 
      try 
      { 
       SqlDataReader reader = _command.EndExecuteReader(ar); 
       if (reader != null && reader.HasRows) 
       { 
        // Get the image returned in the query 
        reader.Read(); 
        try 
        { 
         byte[] image = (byte[])reader[0]; 
         // WRite the image into the HTTP response output stream 
         _context.Response.ContentType = "image/png"; 
         // strip off the 78 byte Ole header (a relic from old MS Access databases) 
         _context.Response.OutputStream.Write(image, 78, image.Length - 78); 
        } 
        catch 
        { 

        } 
       } 
      } 
      finally 
      { 
       if (_connection != null) 
        _connection.Close(); 
      } 
     } 
    } 
} 

WEBPAGE.NET

<asp:Image ID="HomeTeamImage" runat="server" ImageUrl='<%# "DisplayImage.cs?Logo=" + Eval("HomeTeam") %>' 

的HomeTeam在評估和演示是一個標籤,因爲我正在來自會議的文本[「HomeTeam」]

代碼隱藏

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Collections; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.IO; 

namespace RocoSportsWA.Reporter 
{ 
    public partial class LiveGameReporting : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      Match.Text = Session["HomeTeam"] + " vs. " + Session["AwayTeam"]; 
      DateTime.Text = "Date: " + Session["Date"]; 
      Stadium.Text = "Stadium: " + Session["Stadium"]; 
      HomeTeam.Text = "" + Session["HomeTeam"]; 
      AwayTeam.Text = "" + Session["AwayTeam"]; 

      SqlConnection conn = new SqlConnection("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"); 
      conn.Open(); 


       SqlCommand HomeTeamcmd = new SqlCommand("SELECT Logo from TEAM where Team = @HomeTeam", conn); 
       SqlCommand AwayTeamcmd = new SqlCommand("SELECT Logo from TEAM where Team = @AwayTeam", conn); 

       HomeTeamcmd.Parameters.AddWithValue("@HomeTeam", Session["HomeTeam"]); 
       AwayTeamcmd.Parameters.AddWithValue("@AwayTeam", Session["AwayTeam"]); 

       conn.Open(); 
       byte[] HomeTeamImageByte = (byte[])HomeTeamcmd.ExecuteScalar(); 
       byte[] AwayTeamImageByte = (byte[])AwayTeamcmd.ExecuteScalar(); 

       var bitmapImage = new BitmapImage(); 
       bitmapImage.SetSource(new MemoryStream(HomeTeamImageByte)); 
       Image1.Source = bitmapImage; 
     } 

     } 

} 
+0

的可能重複[什麼是顯示從圖像的最佳方式一個在asp.net中的sql server數據庫?(http://stackoverflow.com/questions/612342/w帽子最好的方式來顯示圖像從一個SQL服務器數據庫在ASP網絡)或[bytearray圖像的asp.net](http://stackoverflow.com中「/questions/1738020/bytearray-to-image-asp-net) – stuartd

回答

2

此代碼將一個二進制的blob轉換爲圖像:

var bitmapImage = new BitmapImage(); 
bitmapImage.SetSource(new MemoryStream(imageData)); 
newImage.Source = bitmapImage; 

其中imageDatabyte[]類型。

只要您正確設置數據庫映射,數據將採用正確的格式。

+0

我嘗試過這種方法,但無法識別BitmapImage,因此Image1.Source中的「Source」也無法識別。我無法爲它找到正確的命名空間。這是否是一個asp.net有區別嗎?請你幫我一下嗎? (代碼如下) – Seesharp

+0

conn.Open(); byte [] HomeTeamImageByte =(byte [])HomeTeamcmd.ExecuteScalar(); byte [] AwayTeamImageByte =(byte [])AwayTeamcmd.ExecuteScalar(); var bitmapImage = new BitmapImage(); bitmapImage.SetSource(新的MemoryStream(HomeTeamImageByte)); Image1.Source = bitmapImage; – Seesharp

+0

@Seesharp - 將代碼添加到您的問題。 'BitmapImage'應該可用。您可能需要添加對程序集的引用 - 這可以解釋爲什麼找不到它。 – ChrisF

1

完成此操作最簡單的方法是指出每個圖像標記的src屬性(或者如果您使用的是ASP.NET圖像控件,則將在接受查詢字符串上的圖像ID的ASHX處理程序處的ImageUrl屬性執行相應的SQL查詢,並寫出圖像的響應的OutputStream

這裏是最近的一篇文章顯示如何以異步方式做到這一點:

http://goo.gl/zCYKE

+0

我試圖在頁面上使用處理程序,但它仍然無法正常工作,請您檢查一下上面的代碼,看看問題出在哪裏。 – Seesharp

相關問題