using System;
using System.Drawing;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
namespace WEB
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ValidateCode : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string checkCode = CreateRandomCode(4);
context.Session["CheckCode"] = checkCode.ToLower();
CreateImage(checkCode, context);
}
public bool IsReusable
{
get
{
return false;
}
}
private static string CreateRandomCode(int codeCount)
{
const string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
var rand = new Random();
for (int i = 0; i < codeCount; i++)
{
int t = rand.Next(35);
randomCode += allCharArray[t];
}
return randomCode;
}
private static void CreateImage(string checkCode, HttpContext context)
{
var iwidth = checkCode.Length * 13;
var image = new Bitmap(iwidth, 25);
Graphics g = Graphics.FromImage(image);
var f = new Font("Arial", 12, FontStyle.Bold);
Brush b = new SolidBrush(Color.Black);
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
g.Clear(Color.White);
g.DrawString(checkCode, f, b, 3, 3);
//var blackPen = new Pen(Color.Blue, 0);
//var rand = new Random();
//for (int i = 0; i < 5; i++)
//{
// int y = rand.Next(image.Height);
// g.DrawLine(blackPen, 0, y, image.Width, y);
//}
var rand = new Random();
for (int i = 0; i < 2; i++)
{
g.DrawLine(new Pen(Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255))), rand.Next(20) - 10, rand.Next(20) - 10, rand.Next(image.Width) + 10, rand.Next(image.Height) + 10);
}
for (int i = 0; i < 2; i++)
{
g.DrawArc(new Pen(Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255))), rand.Next(20) - 10, rand.Next(20) - 10, rand.Next(image.Width) + 10, rand.Next(image.Height) + 10, rand.Next(-100, 100), rand.Next(-200, 200));
}
for (int i = 0; i < 2; i++)
{
g.DrawRectangle(
new Pen(Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255))),
rand.Next(2, 128),
rand.Next(2, 38),
15,
15);
}
var ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.BinaryWrite(ms.ToArray());
context.Response.ClearContent();
context.Response.ContentType = "image/Jpeg";
context.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
}
}
<div class="l w60 z14 lh26">验证码</div>
<div class="l w56 s4">
<input id="txtCheckCode" name=keyword accesskey=s maxlength="6" runat="server" />
</div><div class="l w56 m0_8"><img id="imgCheckCode" src="ValidateCode.ashx" /></div><div class="l w56 lh26"><a href="###" onclick="document.getElementById('imgCheckCode').src='ValidateCode.ashx?code='+Math.random()">看不清</a></div>