随机生成文字图片验证码

时间:2023-02-10 23:01:09

 1、随机生成汉字

 //传入你要生成汉字的个数
public string GetGB2312String(int count)
    {
        var random = new Random();
        var bs = new byte[count * 2];
        for (var i = 0; i < count; i++)
        {
            var c = GetGB2312Char(random);
            bs[i * 2] = (byte)(c.X + 0xa0);
            bs[i * 2 + 1] = (byte)(c.Y + 0xa0);
        }
        return Encoding.GetEncoding("GB2312").GetString(bs);
    }
    Point GetGB2312Char(Random random)
    {
        // 国标一级字(共3755个): 区:16-55, 位:01-94, 55区最后5位为空位
        var 区 = random.Next(40) + 16;
        var 位 = random.Next(区 == 55 ? 89 : 94) + 1;
        return new Point(区, 位);
    }

 

2、添加汉字样式和干扰线

//传入你随机生成的汉字
    public byte[] CreateValidateGraphic(string validateCode)
    {
        Bitmap image = new Bitmap(150, 60);
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机生成器
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            //画图片的干扰线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            //设置字体样式
            Font font = new Font("Verdana", 31, (FontStyle.Bold | FontStyle.Underline));
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
            Color.GreenYellow, Color.DarkRed, 1.2f, true);

            Matrix matrix = new Matrix();
            g.Transform = matrix;
            matrix.Rotate(20);
            g.DrawLine(Pens.Blue, 0, 0, 250, 0);
            g.DrawString(validateCode, font, brush, 3, 2);


            //画图片的前景干扰点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
            //保存图片数据
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            //输出图片流
            return stream.ToArray();
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }

3、保存到项目中

   //汉字传入后返回比特数组
    byte[] by = valid.CreateValidateGraphic(hanzi);

     //比特数组转成流
     MemoryStream stream = new MemoryStream(by);

     //流转成图片
     Image image = Image.FromStream(stream);
     PictureBox pic = new PictureBox();
      pic.Image = image;

      //保存到项目中
      image.Save(@"E:\MyProject\Mytest\Mytest\Image\pic.jpg");

4、结果

随机生成文字图片验证码