如何读取二进制图片-Gridview中显示二进制图片 --2

    上一次描述了如何读取一张图片。现在来讲讲更为实际的使用。在GridView中读取数据库中保存的图片信息。我讲采用vs2005 + sqlServer2000。访问有名的Northwind数据库中的Employee表。其中Employee表中的photo中保存了员工的信息(image类型)。我要做的是讲每一个员工的信息都显示出来包括他们的图片信息。
    注意:
        1.photo中的信息是二进制的,其中有效的图片信息是从第78位开始的。所以当你想要转换图片信息的时候应该从第78位开始。
        2. 我的例子中使用的是<img>显示图片信息的。当然你也可以使用imageWeb控件来显示。我尝试过,如果你使用的是Image控件的话你在调试模式下会报错,但在浏览模式下就是正常的。其原因我也不清楚。各位可以尝试一下。随便也告诉一下我原因。
    下面是代码。
     default.aspx
   

<% @ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"  %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml"   >
< head  runat ="server" >
    
< title > 无标题页 </ title >
</ head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
        
< div  style ="width: 100px; position: static; height: 100px; margin:auto;" >
            
< asp:GridView  ID ="GridView1"  runat ="server"  AutoGenerateColumns ="False"  DataKeyNames ="EmployeeID"
                DataSourceID
="SqlDataSource1"  BackColor ="White"  BorderColor ="#CCCCCC"  BorderStyle ="None"  BorderWidth ="1px"  CellPadding ="3" >
                
< Columns >
                    
< asp:BoundField  DataField ="LastName"  HeaderText ="LastName"  SortExpression ="LastName"   />
                    
< asp:BoundField  DataField ="FirstName"  HeaderText ="FirstName"  SortExpression ="FirstName"   />
                    
< asp:TemplateField >
                        
< EditItemTemplate >
                            
< asp:TextBox  ID ="TextBox1"  runat ="server"  Text ='<%#  Eval("EmployeeID") % > '> </ asp:TextBox >
                        
</ EditItemTemplate >
                        
< ItemTemplate >
                            
< img  ID ="Image1"  src ='<%#  Eval("EmployeeID", "ImageHandler.ashx?id ={0}")  % > ' />
                        
</ ItemTemplate >
                        
< AlternatingItemTemplate >
                            
< img  ID ="Image1"   src ='<%#  Eval("EmployeeID", "ImageHandler.ashx?id ={0}")  % > '/>
                        
</ AlternatingItemTemplate >
                    
</ asp:TemplateField >
                
</ Columns >
                
< FooterStyle  BackColor ="White"  ForeColor ="#000066"   />
                
< RowStyle  ForeColor ="#000066"   />
                
< SelectedRowStyle  BackColor ="#669999"  Font-Bold ="True"  ForeColor ="White"   />
                
< PagerStyle  BackColor ="White"  ForeColor ="#000066"  HorizontalAlign ="Left"   />
                
< HeaderStyle  BackColor ="#006699"  Font-Bold ="True"  ForeColor ="White"   />
            
</ asp:GridView >
        
</ div >
    
    
</ div >
        
< asp:SqlDataSource  ID ="SqlDataSource1"  runat ="server"  ConnectionString ="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand
="SELECT [LastName], [FirstName], [EmployeeID] FROM [Employees]" ></ asp:SqlDataSource >
    
</ form >
</ body >
</ html >

    default.aspx.cs 中不需要任何代码。注意以上的<img ID="Image2"  src='<%# Eval("EmployeeID", " ImageHandler.ashx?id={0}") %>'/>  中的src指向的就是下面你编写的文件。
ImageHandler.ashx
  
<% @ WebHandler Language = " C# "  Class = " ImageHandler "   %>

using  System;
using  System.Web;
using  System.Data;
using  System.Data.SqlClient;
public   class  ImageHandler : IHttpHandler  {
    
    
public void ProcessRequest (HttpContext context) 
    
{
        
//获取雇员ID。
        string id = context.Request.QueryString["id"];
        
//这里可以使用我在上一个例子中读图片的文件的例子来代替。
        
//altimageData的作用是数据库中不存在照片数据的时候可以
        
//显示这个默认的图片。我在这里就用它来代替了。没有实际作用。
        byte[] altimageData = new byte[1];
        
byte[] imageData = altimageData;
        
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
        
{
           
            SqlCommand comm 
= new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @EmployeeID", conn);
            SqlParameter parm 
= comm.Parameters.Add("@EmployeeID", SqlDbType.Int, 4);
            parm.Value 
= int.Parse(id);
            conn.Open(); 
            
using (SqlDataReader rdr = comm.ExecuteReader(CommandBehavior.SingleRow))
            
{
                
if (rdr.Read())
                    
//为了防止你读的数据是空的而做的。如果没有图片就使用替代图片来代替。
                    imageData = (rdr[0== System.DBNull.Value) ? altimageData : (byte[])rdr[0];
            }

         
        }

        
//写入图片信息到输出流中。
        context.Response.OutputStream.Write(imageData, 78, imageData.Length - 78);
    }


    
public bool IsReusable
    
{
        
get {
            
return false;
        }

    }


}

     源代码下载

你可能感兴趣的:(GridView)