2020-08-28

开发工具与关键技术: MVC
作者:罗培发 ;年级:1903 ;撰写时间:2020 年 8 月28日
文献编号: 归档时间: 年 月 日

验证码的随机生成

开发工具与关键技术: MVC
作者:罗培发 
撰写时间:2020.8.28

1、获取随机字符串
public static string GetRandomCode(int intLength)
 {
    (1)产生数字和密码混合的随机数
     string strReturn = string.Empty;
     Random random = new Random();//随机数
     for (int i = 0; i < intLength; i++)
  {
     char cRerult;
     int intRandom = random.Next();产生一个非负随机整数
    (2)根据当前随机数来确定字符串
    intRandom % 3 获取的是intRandom/3 得到的余数
    if (intRandom % 3 == 0)
    {
           产生数字
           位数来产生数字
      cRerult = (char)(0x30 + (intRandom % 10));
      }
        else if (intRandom % 3 == 1)
      {
         位数产生大写字母:大写字符 65-97 A 65
                    68 D  25 Z
                    cRerult = (char)(0x41 + (intRandom % 0x1a));
                }
                else
                {
                    余数为2
                    产生小写字母 98-116
                    cRerult = (char)(0x61 + (intRandom % 0x1a));
                }
                strReturn += cRerult.ToString();
            }
            return strReturn;
        }

2、根据字符串创建验证码
public static byte[] CreateImage(string strRandom)
        {
            (1)新增图片
            Bitmap newBitmap = new Bitmap(strRandom.Length * 20, 38);

            Graphics g = Graphics.FromImage(newBitmap);
            g.Clear(Color.White);
            (2)在图片上绘制文字
            SolidBrush solidBrush = new SolidBrush(Color.Red);
            g.DrawString(strRandom, new Font("Aril", 18), solidBrush, 12, 4);
            (3)在图片上绘制干扰线
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                产生一条线,并绘制到画布。 起始点(x,y)  总结点
                int x1 = random.Next(newBitmap.Width);
                int y1 = random.Next(newBitmap.Height);
                int x2 = random.Next(newBitmap.Width);
                int y2 = random.Next(newBitmap.Height);
                g.DrawLine(new Pen(Color.DarkGray), x1, y1, x2, y2);
            }
            (4)绘制图片的前景干扰点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(newBitmap.Width);
                int y = random.Next(newBitmap.Height);
                newBitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            (5)在最外边绘制边框
            g.DrawRectangle(new Pen(Color.Blue), 0, 0, newBitmap.Width, newBitmap.Height);
            g.DrawRectangle(new Pen(Color.Blue), -1, -1, newBitmap.Width, newBitmap.Height);
            (6)将图转保存到内存流中
            MemoryStream ms = new MemoryStream();
            newBitmap.Save(ms, ImageFormat.Jpeg);
            return ms.ToArray();将流内容写入byte数组返回

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值