using System;
using System.IO;
using System.Web;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
/// <summary>
///Cls_PicVcode生成圖片
/// </summary>
public class ValidateCode
{
/// <summary>
/// 該方法用於生成指定位數的隨機數
/// </summary>
/// <param name="VcodeNum">參數是隨機數的位數</param>
/// <returns>返回一個隨機數字符串</returns>
private string RndNum(int VcodeNum)
{
string Vchar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P" +
",Q,R,S,T,U,V,W,X,Y,Z";
string[] VcArray = Vchar.Split(new Char[] { , });//拆分成數組
string VNum = "";//產生的隨機數
int temp = -1;//記錄上次隨機數值,盡量避免生產幾個一樣的隨機數
Random rand = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(33);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
/// <summary>
/// 該方法是將生成的隨機數寫入圖像文件
/// </summary>
/// <param name="VNum">VNum是一個隨機數</param>
public MemoryStream Create(out string VNum)
{
VNum = RndNum(4);
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
System.Random random = new Random();
//驗證碼顏色集合
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//驗證碼字體集合
string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" };
//定義圖像的大小,生成圖像的實例
Img = new Bitmap(100, 25);
g = Graphics.FromImage(Img);//從Img對象生成新的Graphics對象
g.Clear(Color.White);//背景設為白色
//在隨機位置畫背景點
for (int i = 0; i < 100; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
//驗證碼繪制在g中
for (int i = 0; i < VNum.Length; i++)
{
int cindex = random.Next(7);//隨機顏色索引值
int findex = random.Next(5);//隨機字體索引值
Font f = new System.Drawing.Font(fonts[findex], 14, System.Drawing.FontStyle.Bold);//字體
Brush b = new System.Drawing.SolidBrush(c[cindex]);//顏色
int ii = 4;
if ((i + 1) % 2 == 0)//控制驗證碼不在同一高度
{
ii = 2;
}
g.DrawString(VNum.Substring(i, 1), f, b, 3 + (i * 20), ii);//繪制一個驗證字符
}
ms = new MemoryStream();//生成內存流對象
Img.Save(ms, ImageFormat.Jpeg);//將此圖像以jpg圖像文件的格式保存到流中
//回收資源
g.Dispose();
Img.Dispose();
return ms;
}
}