当前位置: 移动技术网 > IT编程>开发语言>c# > C#生成验证码图片的方法

C#生成验证码图片的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例为大家分享了c#生成验证码图片的具体代码,供大家参考,具体内容如下 /// <summary> /// 生成验证码图片 /

本文实例为大家分享了c#生成验证码图片的具体代码,供大家参考,具体内容如下

/// <summary>
    /// 生成验证码图片
    /// </summary>
    /// <returns></returns>
    public byte[] getverifycode()
    {
      int codew = 80;
      int codeh = 40;
      int fontsize = 18;
      string chkcode = string.empty;
      //颜色列表,用于验证码、噪线、噪点 
      color[] color = { color.black, color.red, color.blue, color.green, color.orange, color.brown, color.brown, color.darkblue };
      //字体列表,用于验证码 
      string[] font = { "times new roman" };
      //验证码的字符集,去掉了一些容易混淆的字符 
      char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y' };
      random rnd = new random();
      //生成验证码字符串 
      for (int i = 0; i < 4; i++)
      {
        chkcode += character[rnd.next(character.length)];
      }

      //创建画布
      bitmap bmp = new bitmap(codew, codeh);
      graphics g = graphics.fromimage(bmp);
      g.clear(color.white);
      //画噪线 
      for (int i = 0; i < 1; i++)
      {
        int x1 = rnd.next(codew);
        int y1 = rnd.next(codeh);
        int x2 = rnd.next(codew);
        int y2 = rnd.next(codeh);
        color clr = color[rnd.next(color.length)];
        g.drawline(new pen(clr), x1, y1, x2, y2);
      }
      //画验证码字符串 
      for (int i = 0; i < chkcode.length; i++)
      {
        string fnt = font[rnd.next(font.length)];
        font ft = new font(fnt, fontsize);
        color clr = color[rnd.next(color.length)];
        g.drawstring(chkcode[i].tostring(), ft, new solidbrush(clr), (float)i * 18, (float)0);
      }
      //将验证码图片写入内存流,并将其以 "image/png" 格式输出 
      memorystream ms = new memorystream();
      try
      {
        bmp.save(ms, imageformat.png);
        return ms.toarray();
      }
      catch (exception)
      {
        return null;
      }
      finally
      {
        g.dispose();
        bmp.dispose();
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网