简单的验证码CS代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace ZitCms1127Exams.images
{
///
/// Handler1 的摘要说明
///
public class Handler1 : IHttpHandler,IRequiresSessionState
{
private Random random = new Random();
private int length=6;
private char[] chars =
{
'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', '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'
};
private string makeChars()
{
var arr = new char[length];
for (int i = 0; i < length; i++)
{
arr[i] = chars[random.Next(chars.Length)];
}
return new string(arr);
}
public void ProcessRequest(HttpContext context)
{
var capcha = makeChars();
context.Session["capcha"] = capcha;
var bytes = createImage(capcha);
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(bytes);
//var fileNameWithoutExt = random.Next(1, 5);
//var fileName = fileNameWithoutExt + ".jpg";
//context.Response.WriteFile(fileName);
//context.Response.BinaryWrite();
}
private byte[] createImage(string capcha)
{
var img = new Bitmap(20 * length, 30);
var gh = Graphics.FromImage(img);
gh.FillRectangle(Brushes.BlanchedAlmond, 0, 0, 20*length, 30);
gh.DrawString(capcha, new Font("新宋体", 20, GraphicsUnit.Pixel), Brushes.BlueViolet, 3, 3);
gh.DrawLine(Pens.Teal, 0, 30, 20*length, 0);
var ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
var bytes = ms.ToArray();
ms.Close();
ms.Dispose();
gh.Dispose();
img.Dispose();
return bytes;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}