一个随机字体、样式、颜色、笔刷的图片验证码。

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace _3gMedia.Code.Utility
{
    /// 
    /// 页面验证码程序
    /// 使用:在页面中加入HTML代码 <img src="VerifyCode.aspx" border="0" />
    /// 
    public class VerifyCode : System.Web.UI.Page
    {
        static string[] FontItems = new string[] {    "Arial", 
                                                      "Helvetica", 
                                                      "Geneva", 
                                                      "sans-serif", 
                                                      "Verdana"
                                                  };

        static Brush[] BrushItems = new Brush[] {     Brushes.OliveDrab,
                                                      Brushes.ForestGreen,
                                                      Brushes.DarkCyan,
                                                      Brushes.LightSlateGray,
                                                      Brushes.RoyalBlue,
                                                      Brushes.SlateBlue,
                                                      Brushes.DarkViolet,
                                                      Brushes.MediumVioletRed,
                                                      Brushes.IndianRed,
                                                      Brushes.Firebrick,
                                                      Brushes.Chocolate,
                                                      Brushes.Peru,
                                                      Brushes.Goldenrod
                                                };

        private static Color BackColor = Color.White;
        private static Pen BorderColor = Pens.DarkGray;
        private static int Width = 50;
        private static int Height = 20;

        private Random _random;
        private string _code;
        private int _brushNameIndex;

        private void Page_Load(object sender, System.EventArgs e)
        {
            //
            // TODO : initialize
            //
            this._random = new Random();
            this._code = GetRandomCode();

            //
            // TODO : use Session["_VerifyCode"] save the VerifyCode
            //
            Session["_VerifyCode"] = this._code;

            //
            // TODO : output Image
            //
            this.SetPageNoCache();
            this.OnPaint();
        }

        /// 
        /// 设置页面不被缓存
        /// 
        private void SetPageNoCache()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
        }

        /// 
        /// 取得一个 4 位的随机码
        /// 
        /// 
  
  
        private string GetRandomCode()
        {
            return Guid.NewGuid().ToString().Substring(0, 4);
        }

        /// 
        /// 随机取一个字体
        /// 
        /// 
  
  
        private Font GetFont()
        {
            int fontIndex = _random.Next(0, FontItems.Length);
            return new Font(FontItems[fontIndex], 12, GetFontStyle());
        }

        /// 
        /// 取一个字体的样式
        /// 
        /// 
  
  
        private FontStyle GetFontStyle()
        {
            switch (DateTime.Now.Second % 2)
            {
                case 0:
                    return FontStyle.Regular | FontStyle.Bold;
                case 1:
                    return FontStyle.Italic | FontStyle.Bold;
                default:
                    return FontStyle.Regular | FontStyle.Bold;
            }
        }

        /// 
        /// 随机取一个笔刷
        /// 
        /// 
  
  
        private Brush GetBrush()
        {
            _brushNameIndex = _random.Next(0, BrushItems.Length);
            return BrushItems[_brushNameIndex];
        }


        /// 
        /// 绘画事件
        /// 
        private void OnPaint()
        {
            Bitmap oBitmap = null;
            Graphics g = null;

            try
            {
                oBitmap = new Bitmap(Width, Height);
                g = Graphics.FromImage(oBitmap);

                Paint_Background(g);
                Paint_Text(g);
                Paint_Stain(oBitmap);
                Paint_Border(g);

                oBitmap.Save(Response.OutputStream, ImageFormat.Gif);
                Response.ContentType = "image/gif";
            }
            catch
            {
                Response.Clear();
                Response.Write("Err!");
                Response.End();
            }
            finally
            {
                if (null != oBitmap)
                    oBitmap.Dispose();
                if (null != g)
                    g.Dispose();
            }
        }

        /// 
        /// 绘画背景色
        /// 
        /// 
        private void Paint_Background(Graphics g)
        {
            g.Clear(BackColor);
        }

        /// 
        /// 绘画边框
        /// 
        /// 
        private void Paint_Border(Graphics g)
        {
            g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
        }

        /// 
        /// 绘画文字
        /// 
        /// 
        private void Paint_Text(Graphics g)
        {
            g.DrawString(_code, GetFont(), GetBrush(), 1, 1);
        }

        /// 
        /// 绘画噪音点
        /// 
        /// 
        private void Paint_Stain(Bitmap b)
        {
            for (int n = 0; n < 30; n++)
            {
                int x = _random.Next(Width);
                int y = _random.Next(Height);
                b.SetPixel(x, y, Color.FromName(BrushItems[_brushNameIndex].ToString()));
            }
        }


        /// 
        /// 对用户输入的验证码进行检测,返回检测结果。
        /// 
        /// 验证码表单值
        /// 
  
  
        public static bool Check(string input)
        {
            if (HttpContext.Current.Session["_VerifyCode"] == null || input == null)
            {
                return false;
            }

            string _code = HttpContext.Current.Session["_VerifyCode"].ToString();
            HttpContext.Current.Session.Remove("_VerifyCode");

            if (_code.ToUpper() != input.ToUpper())
            {
                return false;
            }

            return true;
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值