c#实现的简单验证码

发布时间:2020-11-05编辑:脚本学堂
大家在申请邮箱或用户注册时,经常会遇到输入注册码的情况,以下代码实现了一个简单的验证码功能。

大家在申请邮箱或用户注册时,经常会遇到输入注册码的情况,以下代码实现了一个简单的验证码功能。
有需要的朋友,可以参考下。

复制代码 代码如下:
//注意:源代码端只需要第一行
 
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Drawing;
 using System.Drawing.Imaging;
 using System.IO;
 
 namespace TwoStore.UI.login
 {
     public partial class CodeImage : System.Web.UI.Page
     {
         protected void Page_Load(object sender, EventArgs e)
         {
             DrapingCodes(ValidateCode());
         }
         private string ValidateCode()
         {
             string result = "";
             string[] codes = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f",
                                "g", "h", "i", "j", "k","l", "m", "n", "o", "p","q", "r", "s", "t", "u", "v",
                                "w", "x", "y", "z"};
             //创建随机数
             Random rand = new Random();
             //rand.Next(codes.Length),随机数的长度为数组的长度
             for (int i = 0; i < 4; i++)
             {
                 result += codes[rand.Next(codes.Length)];
             }
             //可以把说的值放在Session中,以判断用户输入的是否显示的验证码
             //也可用Cookie
             Session["code"] = result;
             return result;
         }
         //画图需要导入命名空间System.Drawing;System.Drawing.Imaging;System.IO;                      
         private void DrapingCodes(string code)
         {
             //创建画板---Bitmap---此函数重载12次
             //创建画板时直接规定了它的width,height
             Bitmap bmap = new Bitmap(70, 30);
             //创建画家---并把画布给画家
             Graphics grap = Graphics.FromImage(bmap);
             //让画家把画板图上背景颜色
             grap.Clear(Color.White);
             //创建刷子
             Brush brush = new SolidBrush(Color.Black);
             //创建字体
             Font f = new Font("Comic Sans MS", 15);
 
             //开始绘画
             grap.DrawString(code, f, brush, 10, 2);
 
             //随机数
             Random rand = new Random();
             //打上噪点
             for (int i = 0; i < 50; i++)
             {
                 bmap.SetPixel(rand.Next(70), rand.Next(30), Color.Black);
             }
             //画笔刷子
             Brush b1 = new SolidBrush(Color.Blue);
             //画笔
             Pen p = new Pen(b1);
             //7,画上几条线
             for (int i = 0; i < 3; i++)
             {
                 grap.DrawLine(p, rand.Next(70), rand.Next(30), rand.Next(70), rand.Next(30));
             }
             //定义一个内存流
             MemoryStream ms = new MemoryStream();
             //把图片放到内存流中
             bmap.Save(ms, ImageFormat.Gif);
             //清空输出流
             Response.Clear();
             //设置输出内容的格式
             Response.ContentType = "image/gif";
             //以二进制输出byte[]
             Response.BinaryWrite(ms.ToArray());
             Response.End();
         }
     }
 }