HTTP 处理程序用于处理图像





0/5 (0投票)
您好,在本文中,我将创建一个 http 处理器,用于调整我的图像大小并显示它们。什么是 HTTP 处理器?HTTP 处理器是
您好,
在本文中,我将创建一个 http 处理器,用于调整我的图像大小并显示它们。
什么是 HTTP 处理器?
HTTP 处理器是实现 System.Web.IHttpHandler 接口的 .NET 组件,它们可以充当传入 HTTP 请求的目标,并且可以通过在 URL 中使用它们的文件名直接调用。
HTTP 处理器实现了以下两种方法
1) ProcessRequest:用于处理 http 请求,以及
2) IsReusable,它指示此 http 处理器实例是否可以重复用于满足相同类型的其他请求。
在您的网站中,添加新的项目“通用处理器”,并将其命名为 ImageHandler.ashx
这是 ImageHandler.ashx 文件
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.IO;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string sImageFileName = "";
int iThumbSize = 0;
decimal dHeight, dWidth, dNewHeight, dNewWidth;
sImageFileName = context.Request.QueryString["img"];
iThumbSize = Convert.ToInt32(context.Request.QueryString["sz"]);
System.Drawing.Image objImage = System.Drawing.Bitmap.FromFile(System.Web.HttpContext.Current.Server.MapPath("Image Path" + sImageFileName));
if (sImageFileName != null)
{
if (iThumbSize == 1)
{
dHeight = objImage.Height;
dWidth = objImage.Width;
dNewHeight = 120;
dNewWidth = dWidth * (dNewHeight / dHeight);
objImage = objImage.GetThumbnailImage((int)dNewWidth, (int)dNewHeight, new System.Drawing.Image.GetThumbnailImageAbort(callback), new IntPtr());
}
if (iThumbSize == 2)
{
dHeight = objImage.Height;
dWidth = objImage.Width;
dNewHeight = 200;
dNewWidth = dWidth * (dNewHeight / dHeight);
objImage = objImage.GetThumbnailImage((int)dNewWidth, (int)dNewHeight, new System.Drawing.Image.GetThumbnailImageAbort(callback), new IntPtr());
}
MemoryStream objMemoryStream = new MemoryStream();
objImage.Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageContent = new byte[objMemoryStream.Length];
objMemoryStream.Position = 0;
objMemoryStream.Read(imageContent, 0, (int)objMemoryStream.Length);
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(imageContent);
}
}
private bool callback()
{
return true;
}
public bool IsReusable
{
get
{
return false;
}
}
}
以下是编写它的方式..
<img id="Image1" src='../ImageHandler.ashx?img=ImageName&sz=1' />