2012-11-17 2 views
0

SQL 서버 데이터베이스에 바이너리 데이터로 저장된 이미지가 있습니다. 이제 저는 Gridview에이 이미지들을 보여주고 싶습니다. 그러나 데이터베이스에서 직접 데이터를 읽는 웹 컨트롤이 있습니다. 웹 이미지 컨트롤은 ImageUrl 속성이 필요하므로 내 이미지가 데이터베이스에 있으므로이 기능을 사용할 수 없습니다. 그러나 폴더에있는 이미지를 저장할 수 있지만 직접 데이터베이스에서 이미지 데이터를 읽고 눈금에 표시 할 수있는 다른 방법을 원합니다.데이터베이스에서 GridView에 이미지를 표시 하시겠습니까?

+0

당신은 SO의 기존 답변 검색을 수행 했습니까? – IrishChieftain

+0

예, 할 수 있지만 적절한 찾을 수 없습니다 –

+0

http://stackoverflow.com/search?q=asp.net+images+database+httphandler – IrishChieftain

답변

2

를 제공 할 수 있습니다 당신은 이미지로 바이너리 데이터를 변환하고 표시 할 수 있습니다 그것을

코드 : 설정 이미지 컨트롤의 URL을 Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

로 여기서 ShowImage.ashx는 제네릭 처리기 파일입니다.

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

public class ShowImage : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     Int32 empno; 
     if (context.Request.QueryString["id"] != null) 
      empno = Convert.ToInt32(context.Request.QueryString["id"]); 
     else 
      throw new ArgumentException("No parameter specified"); 

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

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

    public Stream ShowEmpImage(int empno) 
    { 
     string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; 
     SqlConnection connection = new SqlConnection(conn); 
     string sql = "SELECT* FROM table WHERE empid = @ID"; 
     SqlCommand cmd = new SqlCommand(sql,connection); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.AddWithValue("@ID", empno); 
     connection.Open(); 
     object img = cmd.ExecuteScalar(); 
     try 
     { 
      return new MemoryStream((byte[])img); 
     } 
     catch 
     { 
      return null; 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 
} 

블로그 기사 : Save and retrieve image from binary data asp.net c#

+0

핸들러에서 직접 이미지를 가져 옵니까? –

+0

@eraj : 네, 제 경우에는 이것이 작동합니다. 잘 jst 한 번 시도하고 내가 무슨 문제를 찾으면 knw 알려주시겠습니까? –

관련 문제