在 ASP.NET 中显示二进制图像的控件
RbmBinaryImage 控件将帮助您直接从数据库显示图像。您可以将 Image 字段直接绑定到 ImageContent 属性,并指定是否希望以缩略图形式显示,并提供缩略图大小。
引言
RbmBinaryImage
控件将帮助您直接从数据库显示图像。您可以将 Image
字段直接绑定到 ImageContent
属性。此外,您可以指定是否希望以缩略图形式显示图像,并指定一个在 ImageContent
为空时显示的图像。另一种方法是通过代码实现
使用 RbmBinaryImage 控件
首先,您需要添加引用 RbmControls.dll,然后在 web.config 的 system.web
部分中放置以下代码。
<httpHandlers>
<add verb="GET" path="__RbmImageHandler.rbm"
type="RbmControls.RbmImageHandler" />
</httpHandlers>
然后,在您想要使用该控件的页面中,使用以下方式注册它
<%@ Register Assembly="RbmControls" Namespace="RbmControls" TagPrefix="Rbm" %>
您可以直接使用 ImageContent
属性绑定控件。此外,您可以指定是否将图像显示为缩略图,并指定在 ImageContent
为空时显示的图像。另一种方法是通过代码实现
RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
Using the Code
RbmBinaryImage
类继承自 System.Web.UI.WebControls.Image
并添加了存储和渲染二进制图像的功能。它还添加了根据指定大小生成缩略图以及缓存图像的能力。
Imagecontent
属性检索并将图像字节存储在 ViewState 中。此外,如果将 DisplayThumbnail
属性设置为 true
,则它将检索图像的缩略图
public byte[] ImageContent
{
get
{
byte[] imageBytes = ViewState["ImageContent"] as byte[];
if (!DisplayThumbnail)
return (imageBytes == null) ? null : imageBytes;
else if (imageBytes != null)
{
byte[] bytes = CreateThumb();
return bytes;
}
else
return null;
}
set
{
ViewState["ImageContent"] = value;
}
}
OnPreRender
方法用于根据 Image 控件的属性设置设置 ImageUrl
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (DesignMode)
return;
if (ImageContent != null)
{
if(string.IsNullOrEmpty(CacheKey))
CacheKey = "Rbm" + System.DateTime.Now.Ticks;
ImageUrl = String.Format("~/__RbmImageHandler.rbm?MimeType={0}" +
"&EnableCaching={1}&ImageContent={2}",
MimeType, EnableCachinge ? "1" : "0", CacheKey);
if(this.Context.Cache[CacheKey] == null)
this.Context.Cache[CacheKey] = ImageContent;
}
else if (ImageUrl == "" || ImageUrl == null)
{
ImageUrl = EmptyImageUrl;
}
}
RbmImageHandler
类实现了 IHttpHandler
接口并重写了 ProcessRequest
方法以显示图像
public void ProcessRequest(HttpContext context)
{
#region Caching Properties
string cacheKey = context.Request["ImageContent"];
if (String.IsNullOrEmpty(cacheKey))
return;
bool enableCaching = false;
if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
#endregion
#region Image Properties
string mimeType = context.Request["MimeType"];
if (string.IsNullOrEmpty(mimeType))
mimeType = "image/jpeg";
byte []imageData = context.Cache[cacheKey] as byte[];
#endregion
if (!enableCaching)
context.Cache.Remove(cacheKey);
context.Response.ContentType = mimeType;
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
分享您的想法
如果您喜欢该控件或对其有任何评论,或者想要添加的功能,请在此处分享您的想法。