在DataGrid中显示使用内存流的图片(转译)

下面又是一篇转译自外国网站的控件开发文章:

文章主要介绍了一个用来显示图片的自定义控件,当然在DATAGRID或其它的列表控件中显示图片有很多方式,但以下这种方式让你的代码看起来更清淅,执行效率会更高.它不用在调用另一个网页,对每一个图片进行数据库查询处,它只是在绑定过程中就处理了来自数据库的数据.

以下是控件源码:

None.gif using  System;
None.gif
using  System.Collections.Specialized;
None.gif
using  System.Drawing;
None.gif
using  System.Drawing.Imaging;
None.gif
using  System.IO;
None.gif
using  System.Web;
None.gif
using  System.Web.SessionState;
None.gif
using  System.Web.UI;
None.gif
using  System.Web.UI.Design;
None.gif
using  System.Web.UI.WebControls;
None.gif
using  System.Reflection ;
None.gif
using  System.ComponentModel;
None.gif
None.gif
namespace  PAB.WebControls
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif 
public enum ImageType
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif   Gif,
InBlock.gif   Jpeg
ExpandedSubBlockEnd.gif }

InBlock.gif
InBlock.gif 
public enum Persistence
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  Cache,
InBlock.gif  Session   
ExpandedSubBlockEnd.gif }

InBlock.gif  
InBlock.gif [Designer(
"PAB.WebControls.ImageControlDesigner"),
InBlock.gif        ToolboxDataAttribute(
"<{0}:ImageControl Runat=\"server\"></{0}:ImageControl>")]
InBlock.gif    
public class ImageControl : Control
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
protected string ImageUrl;  
InBlock.gif  
private ImageType imageType;
InBlock.gif  [Description(
"Image Type")]
InBlock.gif  [Category(
"Data")]
InBlock.gif  [DefaultValue(
"Gif")]
InBlock.gif  [Browsable(
true)]
InBlock.gif  
public ImageType ImageType
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
get
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{     
InBlock.gif    
return imageType;
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   
set
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    imageType
=value;
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private Persistence persistenceType;
InBlock.gif
InBlock.gif  [Description(
"Cache or Session Persistence")]
InBlock.gif  [Category(
"Data")]
InBlock.gif  [DefaultValue(
"Cache")]
InBlock.gif  [Browsable(
true)]
InBlock.gif  
public Persistence PersistenceType
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
get
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{     
InBlock.gif    
return persistenceType;
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   
set
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    persistenceType
=value;
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private Bitmap _bitmap;
InBlock.gif       [Browsable(
false)]
InBlock.gif        
public Bitmap Bitmap
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               
if(this.PersistenceType==Persistence.Session )
InBlock.gif                   
return (Bitmap)Context.Session[String.Concat(CreateUniqueIDString(), "Bitmap")];
InBlock.gif      
else 
InBlock.gif         
return (Bitmap)Context.Cache[String.Concat(CreateUniqueIDString(), "Bitmap")];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif    
if(this.PersistenceType==Persistence.Session)
InBlock.gif                Context.Session[String.Concat(CreateUniqueIDString(), 
"Bitmap")] = value;
InBlock.gif    
else 
InBlock.gif       Context.Cache[String.Concat(CreateUniqueIDString(), 
"Bitmap")] = value;
InBlock.gif    
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private string CreateUniqueIDString()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{   
InBlock.gif           
string idStr=String.Empty;
InBlock.gif   
string tmpId=String.Empty;
InBlock.gif   
ifthis.PersistenceType ==Persistence.Session )
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    idStr 
= "__" +Context.Session.SessionID.ToString() +"_";
ExpandedSubBlockEnd.gif   }

InBlock.gif   
else
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
if(Context.Cache["idStr"]==null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif                   tmpId
=Guid.NewGuid().ToString();
InBlock.gif     Context.Cache[
"idStr"]=tmpId;    
ExpandedSubBlockEnd.gif    }

InBlock.gif    idStr
= "__"+Context.Cache["idStr"].ToString() +"_";
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif            idStr 
= String.Concat(idStr, UniqueID);
InBlock.gif            idStr 
= String.Concat(idStr, "_");
InBlock.gif            idStr 
= String.Concat(idStr, Page.ToString());
InBlock.gif            idStr 
= String.Concat(idStr, "_");    
InBlock.gif            
return idStr;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void ImageControl_Init(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            HttpRequest httpRequest 
= Context.Request;
InBlock.gif            HttpResponse httpResponse 
= Context.Response;
InBlock.gif            
if (httpRequest.Params[String.Concat("ImageControl_", UniqueID)] != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                httpResponse.Clear();               
InBlock.gif    
if(this.ImageType==ImageType.Gif)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    httpResponse.ContentType 
= "Image/Gif";
InBlock.gif     Bitmap.Save(httpResponse.OutputStream,ImageFormat.Gif );
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    httpResponse.ContentType 
= "Image/Jpeg";
InBlock.gif                    Bitmap.Save(httpResponse.OutputStream, ImageFormat.Jpeg);
ExpandedSubBlockEnd.gif                }

InBlock.gif                httpResponse.End();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
string str = httpRequest.Url.ToString();
InBlock.gif            
if (str.IndexOf("?"== -1)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                ImageUrl 
= String.Concat(str, "?ImageControl_", UniqueID, "=1");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                ImageUrl 
= String.Concat(str, "&ImageControl_", UniqueID, "=1");
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ImageControl_Init(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif  
InBlock.gif        
protected override void Render(HtmlTextWriter output)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            output.Write(
"<img id={0} src={1}>",  this.UniqueID,ImageUrl  );
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif 
public class ImageControlDesigner: System.Web.UI.Design.ControlDesigner
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif  
public ImageControlDesigner()dot.gif{}
InBlock.gif  
public override string GetDesignTimeHtml()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
return  GetEmptyDesignTimeHtml ();
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
protected override string GetEmptyDesignTimeHtml()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif
InBlock.gif   
return CreatePlaceHolderDesignTimeHtml( "<div>[Image is set at runtime. Place 
InBlock.gif
control inside Table TD or DIV for absolute positioning.]</div>");
ExpandedSubBlockEnd.gif
  }

ExpandedSubBlockEnd.gif }

ExpandedBlockEnd.gif}

None.gif
None.gif

下面就是具体的应用了:
下面是写到绑定DG控件的HTML代码:
None.gif < asp:DataGrid  id ="DataGrid1"  style ="Z-INDEX: 101; LEFT: 352px; POSITION: absolute; TOP: 216px"
None.gifrunat
="server"  AutoGenerateColumns ="False" >
None.gif
< Columns >
None.gif
< asp:BoundColumn  DataField ="name"  HeaderText ="Name" ></ asp:BoundColumn >
None.gif
< asp:TemplateColumn  HeaderText ="Image" >
None.gif
< ItemTemplate >
None.gif
< cc1:ImageControl  id ="ImageControl1"  Runat ="server" ></ cc1:ImageControl >
None.gif
</ ItemTemplate >
None.gif
< EditItemTemplate >
None.gif
< asp:TextBox  id ="TextBox1"  runat ="server" ></ asp:TextBox >
None.gif
</ EditItemTemplate >
None.gif
</ asp:TemplateColumn >
None.gif
</ Columns >
None.gif
</ asp:DataGrid >  
None.gif
None.gif
我们从样例数据库Northwind 中得到以下数据表Employees:
None.gif private   void  Page_Load( object  sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            SqlConnection cn;
InBlock.gif            cn 
= new SqlConnection
InBlock.gif                (
"DATABASE=northwind;SERVER=localhost;UID=sa;");
InBlock.gif            String cmdText 
= "SELECT top 4 lastname as name, photo as image FROM Employees";            
InBlock.gif            SqlDataAdapter da 
= new SqlDataAdapter(cmdText,cn);
InBlock.gif            DataSet ds
=new DataSet();
InBlock.gif            da.Fill(ds);
InBlock.gif            DataTable tbl 
= ds.Tables[0];            
InBlock.gif            DataGrid1.DataSource
=tbl;
InBlock.gif            DataGrid1.DataBind();
ExpandedBlockEnd.gif        }

None.gif
在该DG控件的绑定代码中我们写下列代码:
None.gif private   void  DataGrid1_ItemDataBound( object  sender, DataGridItemEventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {            
InBlock.gif        MemoryStream ms
=null;        
InBlock.gif        PAB.WebControls.ImageControl ctrl
=null;
InBlock.gif            
byte[] b=null;
InBlock.gif            
if ( e.Item.ItemType == ListItemType.AlternatingItem ||
InBlock.gif                   e.Item.ItemType 
== ListItemType.Item)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif            b 
= (byte[])(DataBinder.Eval(e.Item.DataItem, "image"));                
InBlock.gif            ms 
= new MemoryStream();
InBlock.gif                
// 78 is the size of the OLE header for Northwind images, need to strip it off                
InBlock.gif
            int offset = 78;                 
InBlock.gif            ms.Write(b, offset, b.Length
-offset);
InBlock.gif            ctrl 
= (PAB.WebControls.ImageControl)e.Item.FindControl("ImageControl1");
InBlock.gif            ctrl.Bitmap
=(Bitmap)System.Drawing.Image.FromStream(ms);                    
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

None.gif

We need a MemoryStream for this operation. If the item being databound is a regular data display row, we cast the Item.DataItem "image" DataRowView Column to a byte array. In this particular case, Images in the Northwind Employees table were designed from MS Access, which expects a 78 byte OLE header, which we'll strip off. We write the rest of the array into our MemoryStream. Finally, we cast the e.Item.FindControl("ImageControl1") to an instance of my PAB.WebControls.ImageControl, assign the Image to it's Bitmap property, and -- voila! here's what we get:

在这个操作过程当中,我们需要MemoryStream流,如果被绑定的列是普通列的话,我们要把这个列转化为"IMAGE"格式的列.在MS ACCESS数据库中,有前78字节的OLE HEADER,这是自动加上去的,我们要把它去掉,把余下的写入到我们的MemoryStream流当中.
原文章出处和执行结果:请参见!

转载于:https://www.cnblogs.com/lgp/archive/2005/10/15/255436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值