1、命名空间
using System.Drawing;
2、用到的类
Bitmap:画板(译:位图)
Graphics:画笔(译:绘图板)
3、用到的方法
FillRectangle:填充矩形内部
DrawString:画字符
DrawLines:画线条
<%@ WebHandler Language="C#" Class="_02_简单验证码" %>
using System;
using System.Web;
//1:添加命名空间
using System.Drawing;
public class _02_简单验证码 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//2:修改ContentType的值为图片
context.Response.ContentType = "image/jpeg";
//获得4为验证码字符
string checking = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//3:
string che = Checking(checking);
//4:创建画板
using (Bitmap bitmap = new Bitmap(80,40))
{
//5:创建画笔
using (Graphics g = Graphics.FromImage(bitmap))
{
//画一个边框
g.FillRectangle(Brushes.Green, 0, 0, bitmap.Width, bitmap.Height);
g.FillRectangle(Brushes.White, 1, 1, bitmap.Width -2, bitmap.Height -2);
//开始画线条
Drap(bitmap, g);
//画验证码
g.DrawString(che, new Font("楷体", 16), Brushes.Black, 8, 5);
//把图片输出到浏览器
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
/// <summary>
/// 生成4为验证码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Checking(string str)
{
string st = null;
Random ran = new Random();
for (int i = 0; i < 4; i++)
{
st += str[ran.Next(0,61)];
}
return st;
}
/// <summary>
/// 画线条
/// </summary>
/// <param name="bit"></param>
/// <param name="g"></param>
public void Drap(Bitmap bit,Graphics g)
{
Random ran = new Random();
Pen pen = new Pen(Color.Black, 2);
for (int i = 0; i < 2; i++)
{
int num1 = ran.Next(10, 30);
int num2 = ran.Next(1, 30);
PointF[] points = {
new Point(8,num1),
new Point(70,num2)
};
g.DrawLines(pen, points);
}
}
public bool IsReusable {
get {
return false;
}
}
}
![](https://img-my.csdn.net/uploads/201209/09/1347185750_1075.jpg)