2011-03-31 140 views
1

如何使用C#從SQL數據庫檢索圖像?如何使用C#從SQL數據庫檢索圖像?

+3

Google「Display Blob Image C#」 – 2011-03-31 09:47:34

+0

您的方法是什麼?爲什麼它不工作(異常消息,編譯器錯誤...)? – 2011-03-31 09:48:15

+0

繼續吧,先試試吧,如果你被困在某個地方,就會復出! – 2011-03-31 09:51:57

回答

0

爲什麼不嘗試使用查詢字符串。這裏是我的代碼,在查詢字符串中使用,我從數據庫中獲取圖像,而不必在您的本地文件夾中創建任何想要的圖像的instatnce。跳這有助於。

<%@ WebHandler Language="C#" Class="DisplayImg" %> 

using System; 
using System.Web; 
using System.Configuration; 
using System.IO; 
using System.Data; 
using System.Data.SqlClient; 

public class DisplayImg : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     string theID; 
     if (context.Request.QueryString["id"] != null) 
      theID = context.Request.QueryString["id"].ToString(); 
     else 
      throw new ArgumentException("No parameter specified"); 

     context.Response.ContentType = "image/jpeg"; 
     Stream strm = DisplayImage(theID); 
     byte[] buffer = new byte[2048]; 
     int byteSeq = strm.Read(buffer, 0, 2048); 

     while (byteSeq > 0) 
     { 
      context.Response.OutputStream.Write(buffer, 0, byteSeq); 
      byteSeq = strm.Read(buffer, 0, 2048); 
     } 
    } 

    public Stream DisplayImage(string theID) 
    { 
     SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString()); 
     string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID"; 
     SqlCommand cmd = new SqlCommand(sql, connection); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.AddWithValue("@ID", theID); 
     connection.Open(); 
     object theImg = cmd.ExecuteScalar(); 
     try 
     { 
      return new MemoryStream((byte[])theImg); 
     } 
     catch 
     { 
      return null; 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

只需添加一行在CS代碼

UploadImg.ImageUrl = 「〜/ DisplayImg.ashx ID =?」 +代碼;

+0

-1不使用'using',不檢查空值,並返回方法中的'stream'。 – avishayp 2012-11-16 07:31:07

相關問題