C# 生成验证码

验证码的作用嘛,基本就是用来防暴力破解,防恶意攻击、注册;

即便现在人工智能的高潮兴起,OCR的广泛应用;许多的验证码已经形同虚设,但是做一个项目,该有的基础验证我还是得有;你破你的,我防我的,大家开心就行。

一个简单的验证码的生成方法;

实现功能:

随机生成验证码并显示到pictureBox

开发环境:

开发工具:Visual Studio 2013

.NET Framework版本:4.5

实现代码:

private void GenerateCode(int codeLen = 6) 
{

  string code = "";

  //生成随机数字

  Random rand = new Random();

  for (int i = 0; i < codeLen; i++)

  {

    code += rand.Next(0, 9).ToString();

  }

  /*这里将code保存下来做比对验证*/

  //生成验证码图片并显示到pictureBox1

  byte[] bytes = GenerateImg(code);

   MemoryStream ms = new MemoryStream(bytes);

  Image image = System.Drawing.Image.FromStream(ms);

  pictureBox1.Image = image;

}


/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public byte[] GenerateImg(string code)
{
  Bitmap image = new Bitmap(code.Length * 10, 25);

Graphics g = Graphics.FromImage(image);

try

{

   //清空图片背景色

   g.Clear(Color.White);

//增加背景干扰线
Random random = new Random();

for (int i = 0; i < 30; 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.FromArgb(186, 212, 231)), x1, y1, x2, y2);

   }

//定义验证码字体
Font font = new Font("Arial", 10, (FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout));

//定义验证码的刷子,这里采用渐变的方式,颜色可自定义

LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(67, 93, 230), Color.FromArgb(70, 128, 228), 1.5f, true);

//增加干扰点
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.DrawString(code, font, brush, 5, 5);

//图片边框
    g.DrawRectangle(new Pen(Color.FromArgb(93, 142, 228)), 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();

  }

}
//给pictureBox1添加一个点击刷新的功能
private void pictureBox1_Click(object sender, EventArgs e)
{

  GenerateCode();

}

//直接调用即可
GenerateCode();
posted @ 2022-01-24 14:46  华翎科技  阅读(276)  评论(0)    收藏  举报