zoukankan      html  css  js  c++  java
  • 简单验证码

    许多网站都会有验证码输入。今天就写个简单验证码控件,新建一个固定图片作为画布,在画布画上随机的4个字符,保存图片。用pictureBox控件装载该图片

    效果图:

    外面调用CreateYZM()方法生成验证码,Code属性获取验证码的值,用于验证判断使用

    每点击验证码,都会重新生成

    代码如下:

     1 //验证码
     2         public string Code { get;private set; }
     3         //验证码长度
     4         private int length = 4;
     5 
     6 
     7         //是否有噪点
     8         private bool hasZaoDian = true;
     9         public bool HasZaoDian { get; set; }
    10 
    11         string str = "asdfghjklzxcvbnmqwertyuiopQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";
    12         Random rd = new Random();
    13         public void CreateYZM()
    14         { 
    15            Bitmap image =new Bitmap(65,23);
    16            Graphics gc =  Graphics.FromImage(image);
    17            gc.Clear(Color.YellowGreen);
    18            char[] codeChar = str.ToCharArray();
    19            int index = 0;
    20            StringBuilder code = new StringBuilder();
    21            for ( int i = 0 ; i < length ;i++ )
    22            {
    23               index = rd.Next(0,str.Length);
    24               code.Append(codeChar[index].ToString());
    25            }
    26            Code = code.ToString();
    27            gc.DrawString(code.ToString() , new Font("Couriew New" , 14f , FontStyle.Bold) , new SolidBrush(Color.Red) , new PointF(2 , 1));
    28            if ( hasZaoDian )  //是否画噪点,默认yes
    29            {
    30                for ( int i = 0 ; i < 80 ; i++ )
    31                {
    32                    int x = rd.Next(image.Width);
    33                    int y = rd.Next(image.Height);
    34                    image.SetPixel(x , y , Color.FromArgb(rd.Next()));
    35                }
    36            }
    37            pictureBox1.Image = image;
    38            gc.Dispose();
    39         }
    40 
    41         private void pictureBox1_Click(object sender , EventArgs e)
    42         {
    43             CreateYZM();
    44         }
  • 相关阅读:
    【软件】Linux图形软件VNC&X11
    【C++语法】STL
    【C++语法】Type & Value Category
    【C++语法】关键字
    【C++语法】C++语法目录
    【算法·Algorithms】 Sort
    【代码·Patten】theme: Calculator
    centos MIT 6.828 qemu 安装问题
    【归纳】Layui table.render里的json后台传入
    【归纳】springboot中的IOC注解:注册bean和使用bean
  • 原文地址:https://www.cnblogs.com/bbthome/p/3386366.html
Copyright © 2011-2022 走看看