首页 > 代码库 > 在一般处理程序里写一个简单验证码

在一般处理程序里写一个简单验证码

QQ:675556820

代码不多,直接粘贴了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<%@ WebHandler Language="C#" Class="验证码" %>
 
using System;
using System.Web;
using System.Drawing;
public class 验证码 : IHttpHandler
{
 
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        string code = GetCode();//获得随机数
        using (Image img = GetImg(code))
        {
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
 
 
    private Image GetImg(string code)
    {
        Bitmap bit = new Bitmap(90, 35);
        using (Graphics g = Graphics.FromImage(bit))
        {
            g.FillRectangle(Brushes.Brown, 0, 0, bit.Width, bit.Height);
            g.FillRectangle(Brushes.White, 1, 1, bit.Width - 2, bit.Height - 2);
            g.DrawString(code, new Font("微软雅黑", 20), Brushes.Sienna, 3, 1);
        }
        return bit;
    }
 
    //生成四位验证码
    private string GetCode()
    {
        string code = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string str = "";
        Random r = new Random();
        for (int i = 0; i < 4; i++)
        {
            int index = r.Next(0, code.Length);
            str += code[index];
        }
        return str;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
}