public class RandomHandler : IHttpHandler,IRequiresSessionState
{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/gif";
Bitmap map = new Bitmap(110,23);
Graphics g = Graphics.FromImage(map);
g.Clear(Color.White);
this.DrawPoint(ref g);
this.DrawLine( ref g);
Color codeColor=Color.FromArgb(RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255));
string code = RandomBuilder.GetRandomCode(6);
context.Session["Code"] = code;
g.DrawString(code,new Font("Arial Black",14),new SolidBrush(codeColor),new PointF(0.0f,0.0f));
g.Flush();
g.Dispose();
map.Save(context.Response.OutputStream,ImageFormat.Jpeg);
context.Response.End();
map.Dispose();
}
private void DrawPoint(ref Graphics g)
{
int pointCount = RandomBuilder.Next(30,70);
for(int i =0;i<pointCount;i++)
{
g.DrawRectangle(new Pen(
new SolidBrush(Color.FromArgb(RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255)
))
), RandomBuilder.Next(0, 100), RandomBuilder.Next(0, 30)
,1,1
);
g.Flush();
continue;
}
}
private void DrawLine(ref Graphics g)
{
int lineCount = RandomBuilder.Next(1, 10);
for (int i = 0; i < lineCount; i++)
{
int x1=RandomBuilder.Next(0,100);
int x2=RandomBuilder.Next(0,100);
int y1=RandomBuilder.Next(0,30);
int y2=RandomBuilder.Next(0,30);
g.DrawLines(new Pen(
new SolidBrush(Color.FromArgb(RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255), RandomBuilder.Next(0, 255)
))
),new Point[]{new Point(x1,y1),new Point(x2,y2)}
);
g.Flush();
continue;
}
}
public bool IsReusable {
get {
return false;
}
}
}
调用方法:
<img id="img" src="RandomHandler.ashx" alt="验证码" onclick="this.src='RandomHandler.ashx?'+Math.random();" />