using System;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
namespace zhubj.Page
{
public class ValidateCode:System.Web.UI.Page
{
private const double IMAGELENGTHBASE = 12.5;
private const int IMAGEHEIGTH = 22;
private const int IMAGELINENUMBER = 25;
private const int IMAGEPOINTNUMBER = 100;
public static string VALIDATECODEKEY = "VALIDATECODEKEY";
private int length = 4;
private string code = string.Empty;
/// <summary>
/// 鳳麼扢离桄痐鎢酗僅ㄛ蘇硉峈4﹝
/// </summary>
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
/// <summary>
/// 鳳桄痐鎢
/// </summary>
public string Code
{
get
{
return Code;
}
}
public ValidateCode()
{
}
protected override void OnLoad(EventArgs e)
{
CreateValidateImage(length);
}
/// <summary>
/// 斐膘呴儂桄痐鎢
/// </summary>
/// <param name="length">桄痐鎢酗僅</param>
/// <returns></returns>
public string CreateCode(int length)
{
if(length <= 0) return string.Empty;
///斐膘珨郪呴儂杅ㄛ甜凳傖桄痐鎢
Random random = new Random();
StringBuilder sbCode = new StringBuilder();
for(int i = 0; i < length; i++)
{
sbCode.Append(random.Next(0,10));
}
///悵湔桄痐鎢善Session勤砓笢
code = sbCode.ToString();
Session[VALIDATECODEKEY] = code;
return code;
}
/// <summary>
/// 斐膘桄痐鎢腔芞睿桄痐鎢
/// </summary>
/// <param name="length">桄痐鎢腔酗僅</param>
public void CreateValidateImage(int length)
{ ///斐膘桄痐鎢
code = CreateCode(length);
///斐膘桄痐鎢腔芞
CreateValidateImage(code);
}
/// <summary>
/// 斐膘桄痐鎢腔芞睿桄痐鎢
/// </summary>
/// <param name="code">桄痐鎢</param>
public void CreateValidateImage(string code)
{
if(string.IsNullOrEmpty(code) == true) return;
///悵湔桄痐鎢善Session勤砓笢
Session[VALIDATECODEKEY] = code;
///斐膘珨跺芞砉
Bitmap image = new Bitmap((int)Math.Ceiling((code.Length * IMAGELENGTHBASE)),IMAGEHEIGTH);
Graphics g = Graphics.FromImage(image);
///呴儂杅汜傖
Random random = new Random();
try
{
///諾芞砉ㄛ甜硌隅沓喃晇伎
g.Clear(Color.White);
///餅秶芞腔補盄
int x1,x2,y1,y2;
for(int i = 0; i < IMAGELINENUMBER; i++)
{
x1 = random.Next(image.Width);
y1 = random.Next(image.Height);
x2 = random.Next(image.Width);
y2 = random.Next(image.Height);
///餅秶補盄
g.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2);
}
///餅秶桄痐鎢
Font font = new Font("Tahoma",12,FontStyle.Bold | FontStyle.Italic);
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0,0,image.Width,image.Height),
Color.Blue,Color.DarkRed,1.2f,true);
g.DrawString(code,font,brush,2.0f,2.0f);
///賒芞腔劓婑秞萸
int x,y;
for(int i = 0; i < IMAGEPOINTNUMBER; i++)
{
x = random.Next(image.Width);
y = random.Next(image.Height);
///餅秶萸
image.SetPixel(x,y,Color.FromArgb(random.Next()));
}
///賒芞腔晚遺盄
g.DrawRectangle(new Pen(Color.Silver),0,0,image.Width - 1,image.Height - 1);
///悵湔芞腔囀善霜笢
MemoryStream ms = new MemoryStream();
image.Save(ms,ImageFormat.Gif);
///怀堤芞
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{ ///庋溫梩衄腔訧埭
g.Dispose();
image.Dispose();
}
}
}
}