DrawingOnWebPage.ashx页
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Drawing.Drawing2D;
using System.Drawing;
namespace AspTechnicalBase
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class DrawingOnWebPage : IHttpHandler
{ /// <summary>
/// 绘图的相关参数
/// </summary>
private const int ImageWidth = 600; //指定验证码的宽度
private const int ImageHeight = 100; //指定验证的高度
private const int codeLength = 4;// 指定生成几个验证码
/// <summary>
/// 响应HTTP请求
/// </summary>
/// <param name="context">HTTP请求的上下文对象</param>
public void ProcessRequest(HttpContext context)
{
string str = createCode( codeLength ) as string;
//开辟一个ImageWidth像素宽、ImageHeight像素高的绘图缓冲区
Bitmap bmp = new Bitmap(ImageWidth, ImageHeight);
//创建绘图表面对象,引用这一绘图缓冲区
Graphics g = Graphics.FromImage(bmp);
//生成一个渐变的画刷
Brush br = new LinearGradientBrush(new Point(0, 0), new Point(ImageWidth, 0), Color.Black, Color.Blue);
//用渐变画刷填充绘图表面
g.FillRectangle(br, g.ClipBounds);
Font f = new Font("宋体", 30);
//输出文字
g.DrawString(str, f, Brushes.Yellow, new PointF(40, 20));
//将结果输出到浏览器
context.Response.ContentType = "Image/JPEG";
context.Response.Clear();
context.Response.BufferOutput = true;
bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
//释放相关的绘图对象
br.Dispose();
f.Dispose();
g.Dispose();
bmp.Dispose();
}
/// <summary>
/// 是否自动缓存此对象以供下次复用
/// </summary>
///
private string createCode( int codeLength )
{
string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr = so.Split(',');
string code = "";
Random rand = new Random();
for (int i = 0; i < codeLength; i++)
{
code += strArr[rand.Next(0, strArr.Length)];
}
return code;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
然后是显示验证码的页面 的html中加入<img src="DrawingOnWebPage.ashx" id="poloy" alt="点击刷新" />
在</head>之前一行加入javascript脚本语言如下(当然写在JS文件里面更好):
<script type="text/javascript">
function reloadcode(){
document.getElementById("poloy").src ="DrawingOnWebPage.ashx";
}
</script>