生成验证码图片

<%@ WebHandler Language="C#" Class="ValidateCode" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class ValidateCode : IHttpHandler,IRequiresSessionState {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        string code = GetRndStr();//生成随机字符
        context.Session["code"]=code;//记录验证码
        
        using (Bitmap img = CreateImages(code, "ch"))
        {
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 数字随机数
    /// </summary>
    /// <returns></returns>
    private string GetRndNum()
    {
        string code = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 4; i++)//生成随机字符,个数自己调
        {
            code += random.Next(9);
        }
        return code;
    }
    /// <summary>
    ///  英文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndStr()
    {
        string Vchar = "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";
        string[] VcArray = Vchar.Split(',');
        string checkCode = string.Empty;
        Random rand = new Random();
        for (int i = 0; i < 4; i++)
        {
            int t = rand.Next(VcArray.Length);
            checkCode += VcArray[t];
        }
        return checkCode;
    }
    /// <summary>
    /// 中文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndCh()
    {
        System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页(表)
        object[] bytes = CreateRegionCode(4);//生4个随机中文汉字编码
        string[] str = new string[4];
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 4; i++)
        {
            //根据汉字编码的字节数组解码出中文汉字
            str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
            sb.Append(str[i].ToString());
        }
        return sb.ToString();
    }
    /// <summary>
    /// 产生随机中文字符
    /// </summary>
    /// <param name="strlength"></param>
    /// <returns></returns>
    private static object[] CreateRegionCode(int strlength)
    {
        //定义一个字符串数组储存汉字编码的组成元素
        string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
        Random rnd = new Random();
        object[] bytes = new object[strlength];


        for (int i = 0; i < strlength; i++)
        {
            //区位码第1位
            int r1 = rnd.Next(11, 14);
            string str_r1 = rBase[r1].Trim();
            //区位码第2位
            rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
            int r2;
            if (r1 == 13)
            {
                r2 = rnd.Next(0, 7);
            }
            else
            {
                r2 = rnd.Next(0, 16);
            }
            string str_r2 = rBase[r2].Trim();


            //区位码第3位
            rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机种子
            int r3 = rnd.Next(10, 16);
            string str_r3 = rBase[r3].Trim();


            //区位码第4位
            rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
            int r4;
            if (r3 == 10)
            {
                r4 = rnd.Next(1, 16);
            }
            else if (r3 == 15)
            {
                r4 = rnd.Next(0, 15);
            }
            else
            {
                r4 = rnd.Next(0, 16);
            }
            string str_r4 = rBase[r4].Trim();
            //定义两个字节变量存储产生的随机汉字区位码
            byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
            byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);


            //将两个字节变量存储在字节数组中
            byte[] str_r = new byte[] { byte1, byte2 };


            //将产生的一个汉字的字节数组放入object数组中
            bytes.SetValue(str_r, i);
        }
        return bytes;
    }
    /// <summary>
    /// 画图片的背景图+干扰线 
    /// </summary>
    /// <param name="checkCode"></param>
    /// <returns></returns>
    private Bitmap CreateImages(string checkCode, string type)
    {
        int step = 0;
        if (type == "ch")
        {
            step = 5;//中文字符,边界值做大
        }
        int iwidth = (int)(checkCode.Length * (13 + step));
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 33);
        Graphics g = Graphics.FromImage(image);
        g.Clear(Color.White);//清除背景色
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };//定义随机颜色
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        Random rand = new Random();


        for (int i = 0; i < 50; i++)
        {
            int x1 = rand.Next(image.Width);
            int x2 = rand.Next(image.Width);
            int y1 = rand.Next(image.Height);
            int y2 = rand.Next(image.Height);
            g.DrawLine(new Pen(Color.LightGray, 1), x1, y1, x2, y2);//根据坐标画线
        }


        for (int i = 0; i < checkCode.Length; i++)
        {
            int cindex = rand.Next(7);
            int findex = rand.Next(5);


            Font f = new System.Drawing.Font(font[findex], 15, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(c[cindex]);
            int ii = 4;
            if ((i + 1) % 2 == 0)
            {
                ii = 2;
            }
            g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * (12 + step)), ii);


        }
        g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        return image;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成验证码图片可以使用 Python 中的 Pillow 库和随机数库,具体步骤如下: 1. 导入需要的库: ```python from PIL import Image, ImageDraw, ImageFont import random ``` 2. 定义生成随机字符串的函数: ```python def generate_random_str(length): # 定义随机字符串的备选值 candidates = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # 从备选值中随机选择指定长度的字符串 return ''.join(random.choices(candidates, k=length)) ``` 3. 定义生成验证码图片的函数: ```python def generate_verification_code(width, height, length): # 创建画布 image = Image.new('RGB', (width, height), color=(255, 255, 255)) # 创建画笔 draw = ImageDraw.Draw(image) # 设置字体 font = ImageFont.truetype('arial.ttf', size=30) # 生成随机字符串 code = generate_random_str(length) # 在画布上绘制字符串 for i in range(length): draw.text((10 + i * 20, 10), code[i], font=font, fill=random.choice([(0, 0, 0), (255, 0, 0), (0, 0, 255)])) # 添加干扰点 for i in range(100): draw.point((random.randint(0, width), random.randint(0, height)), fill=(0, 0, 0)) # 添加干扰线 for i in range(5): draw.line([(random.randint(0, width), random.randint(0, height)), (random.randint(0, width), random.randint(0, height))], fill=(0, 0, 0)) # 返回验证码图片和对应的字符串 return image, code ``` 4. 调用函数生成验证码图片: ```python image, code = generate_verification_code(120, 40, 4) image.show() ``` 以上代码中,`generate_random_str` 函数用于生成指定长度的随机字符串,`generate_verification_code` 函数用于生成指定宽度、高度和长度的验证码图片,并返回图片对象和对应的字符串。在绘制字符串时,使用了随机的字体颜色,以及添加了干扰点和干扰线,增加了验证码的复杂度。最后调用 `show` 方法显示生成验证码图片

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值