随机生成验证码

我们经常在网络上能看到一些网站需要输入验证码进行验证,下面这段源码供大家参考:
public class CheckCode
{
    public static void DeawImage()
    {
        CheckCode img = new CheckCode();
        HttpContext.Current.Session["CheckCode"] = img.RandNum(5);
        img.checkCodes(HttpContext.Current.Session["CheckCode"].ToString());
    }
    private void checkCodes(string checkcode)
    {
        int iwidth = (int)(checkcode.Length * 15);
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth,30);
        System.Drawing.Graphics g =  System.Drawing.Graphics.FromImage(image);
        g.Clear(System.Drawing.Color.White);
 
        System.Drawing.Color[] color = {Color.Black,Color.Red,Color.Blue,Color.DarkBlue,Color.Green,Color.Orange,Color.Brown,Color.DarkCyan,Color.Purple };
        string[] font = {"小篆","楷书","黑体","幼圆","宋体" };
        Random rand = new Random();
        //随机噪点
        for (int i = 0; i < 50; i++)
        {
            int x = rand.Next(image.Width);
            int y = rand.Next(image.Height);
            g.DrawRectangle(new Pen(Color.LightGray,0),x,y,1,1);
        }
        //输出不同字体颜色的字符
        for (int i = 0; i < checkcode.Length; i++)
        {
            int cindex = rand.Next(color.Count());
            int findex = rand.Next(font.Count());
            Font f = new Font(font[findex],15,FontStyle.Italic);
            Brush b = new SolidBrush(color[cindex]);
            int ii = 5;
            if ((i + 1) % 2 == 0)
            {
                ii = 2;
            }
            g.DrawString(checkcode.Substring(i,1),f,b,3+(i*10),ii);
        }
        g.DrawRectangle(new Pen(Color.Black,0),0,0,image.Width-1,image.Height-1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ContentType = "image/Jpeg";
        HttpContext.Current.Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }
  //随即字符
    private string RandNum(int num)
    {
        string strcode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        string code = "";
        Random rand = new Random();
        for (int i = 0; i < num; i++)
        {
            code += strcode.Substring(rand.Next(0, strcode.Length), 1);
        }
        return code;
    }
}
原文地址:https://www.cnblogs.com/findchance/p/2670246.html