一个.NET写的类似于google的验证码

在开发B/S结构的应用程序时,登录时为了防止恶意操作,经常要用到验证码,类似的验证码在网上搜一下有很多,无非就是生成一个带有文字的图片,在这里,发布一个类似于google所用的验证码,给大家多一种选择。

效果如图:

代码如下:

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace Mirainsoft.ValidateCode
{
/// <summary>
/// 验证码处理类
/// </summary>
public class ValidateCodeFactory
    {
/// <summary>
/// 字体选择范围数组
/// </summary>
private string[] fonts = { "Times New Roman", "Georgia", "Arial", "Comic Sans MS" };
/// <summary>
/// 验证码取值范围数组
/// </summary>
private string[] CodeScopes = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
///// <summary>
///// 颜色取值范围数组
///// </summary>
//private Color[] ColorScopes = { Color.Crimson, Color.PaleVioletRed, Color.MediumVioletRed, Color.Purple, Color.DarkViolet, Color.Indigo, Color.SlateBlue, Color.DarkSlateBlue, Color.MediumBlue, Color.DarkBlue, Color.SlateBlue, Color.DarkCyan, Color.Gold, Color.Goldenrod, Color.Orange, Color.OrangeRed, Color.Red, Color.DarkRed};
/// <summary>
/// 随机数
/// </summary>
private Random rand;
/// <summary>
/// 随机数种子
/// </summary>
private int randseed;
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;

/// <summary>
/// 显示文本
/// </summary>
public string Text
        {
            get { return this.text; }
        }
/// <summary>
/// 生成的位图对像
/// </summary>
public Bitmap Image
        {
            get { return this.image; }
        }
/// <summary>
/// 验证码宽度
/// </summary>
public int Width
        {
            get { return this.width; }
        }
/// <summary>
/// 验证码高度
/// </summary>
public int Height
        {
            get { return this.height; }
        }

/// <summary>
/// 验证码处理类
/// </summary>
/// <param name="length">显示文本长度,随机生成</param>
/// <param name="width">验证码宽度</param>
/// <param name="height">验证码高度</param>
public ValidateCodeFactory(int length, int width, int height)
        {
this.randseed = 111;
for (int i=0;i<length;i++)
this.text = string.Concat(this.text, CodeScopes[Next(CodeScopes.Length)]);
this.SetDimensions(width, height);
this.SetFamilyName(this.fonts[Next(this.fonts.Length)]);
this.GenerateImage();
        }

/// <summary>
/// 验证码处理类
/// </summary>
/// <param name="s">显示文本</param>
/// <param name="width">验证码宽度</param>
/// <param name="height">验证码高度</param>
public ValidateCodeFactory(string s, int width, int height)
  {
this.randseed = 111;
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(this.fonts[Next(this.fonts.Length)]);
this.GenerateImage();
  }

/// <summary>
/// 验证码处理类
/// </summary>
/// <param name="s">显示文本</param>
/// <param name="width">验证码宽度</param>
/// <param name="height">验证码高度</param>
/// <param name="familyName">字体名称</param>
public ValidateCodeFactory(string s, int width, int height, string familyName)
  {
this.randseed = 111;
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
  }

/// <summary>
/// 垃圾回收
/// </summary>
        ~ValidateCodeFactory()
  {
   Dispose(false);
  }

/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
  {
   GC.SuppressFinalize(this);
this.Dispose(true);
  }

/// <summary>
/// 释放资源
/// </summary>
/// <param name="disposing">是否回收</param>
protected virtual void Dispose(bool disposing)
  {
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
  }

/// <summary>
/// 设置验证码的宽度和高度
/// </summary>
/// <param name="width">验证码宽度</param>
/// <param name="height">验证码高度</param>
private void SetDimensions(int width, int height)
        {
// Check the width and height.
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
        }

/// <summary>
/// 设置显示文本的字体
/// </summary>
/// <param name="familyName">字体名称</param>
private void SetFamilyName(string familyName)
        {
try
            {
                Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
                font.Dispose();
            }
catch
            {
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
            }
        }

/// <summary>
/// 生成验证码
/// </summary>
private void GenerateImage()
        {
// Create a new 32-bit bitmap image.
            Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.
            HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
            g.FillRectangle(hatchBrush, rect);

// Set up the text font.
            SizeF size;
float fontSize = rect.Height + 1;
            Font font;
// Adjust the font size until the text fits within the image.
do
            {
                fontSize--;
                font = new Font(this.familyName, fontSize, FontStyle.Bold);
                size = g.MeasureString(this.text, font);
            } while ((size.Width / 4f )* 3f > rect.Width);

// Set up the text format.
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.
            GraphicsPath path = new GraphicsPath();
            path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 4F;
            PointF[] points =
   {
new PointF(Next(rect.Width) / v, Next(rect.Height) / v),
new PointF(rect.Width - Next(rect.Width) / v, Next(rect.Height) / v),
new PointF(Next(rect.Width) / v, rect.Height - Next(rect.Height) / v),
new PointF(rect.Width - Next(rect.Width) / v, rect.Height - Next(rect.Height) / v)
   };
            Matrix matrix = new Matrix();
            matrix.Translate(0F, 0F);
            path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.
            hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.Gray, Color.Gray);
            g.FillPath(hatchBrush, path);

// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
            {
int x = Next(rect.Width);
int y = Next(rect.Height);
int w = Next(m / 50);
int h = Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }

// Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

// Set the image.
this.image = bitmap;
        }

/// <summary>
/// 获取一个随机数
/// </summary>
/// <returns>int</returns>
private int Next()
        {
            rand = new Random(unchecked((int)DateTime.Now.Ticks) * randseed++);

return rand.Next();
        }
/// <summary>
/// 获取一个随机数
/// </summary>
/// <param name="maxValue">随机数的上界</param>
/// <returns>int</returns>
private int Next(int maxValue)
        {
            rand = new Random(unchecked((int)DateTime.Now.Ticks) * Next());

return rand.Next(maxValue);
        }

/// <summary>
/// 获取一个随机数
/// </summary>
/// <param name="minValue">随机数的下界</param>
/// <param name="maxValue">随机数的上界</param>
/// <returns>int</returns>
private int Next(int minValue, int maxValue)
        {
            rand = new Random(unchecked((int)DateTime.Now.Ticks) * Next());

return rand.Next(minValue, maxValue);
        }
    }
}

posted @ 2010-08-14 17:01  Max Woods  阅读(631)  评论(0编辑  收藏  举报