/// summary>
/// 生成驗(yàn)證碼圖片,保存session名稱VerificationCode
/// /summary>
public static void CreateVerificationCode()
{
int number;
string checkCode = string.Empty;
//隨機(jī)數(shù)種子
Random randoms = new Random();
for (int i = 0; i 4; i++) //校驗(yàn)碼長度為4
{
//隨機(jī)的整數(shù)
number = randoms.Next();
//字符從0-9,A-Z中隨機(jī)產(chǎn)生,對(duì)應(yīng)的ASCII碼分別為
//48-57,65-90
number = number % 36;
if (number 10)
{
number += 48;
}
else
{
number += 55;
}
checkCode += ((char)number).ToString();
}
//在session中保存校驗(yàn)碼
System.Web.HttpContext.Current.Session["VerificationCode"] = checkCode;
//若校驗(yàn)碼為空,則直接返回
if (checkCode == null || checkCode.Trim() == String.Empty)
{
return;
}
//根據(jù)校驗(yàn)碼的長度確定輸出圖片的長度
System.Drawing.Bitmap image = new System.Drawing.Bitmap(55, 20);//(int)Math.Ceiling(Convert.ToDouble(checkCode.Length * 15))
//創(chuàng)建Graphics對(duì)象
Graphics g = Graphics.FromImage(image);
try
{
//生成隨機(jī)數(shù)種子
Random random = new Random();
//清空?qǐng)D片背景色
g.Clear(Color.White);
//畫圖片的背景噪音線 10條
//---------------------------------------------------
for (int i = 0; i 10; i++)
{
//噪音線起點(diǎn)坐標(biāo)(x1,y1),終點(diǎn)坐標(biāo)(x2,y2)
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
//用銀色畫出噪音線
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
//---------------------------------------------------
//Brush b = Brushes.Silver;
//g.FillRectangle(b, 0, 0, image.Width, image.Height);
//---------------------以上兩種任選其一------------------------------
//輸出圖片中校驗(yàn)碼的字體: 12號(hào)Arial,粗斜體
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
//線性漸變畫刷
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Purple, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//畫圖片的前景噪音點(diǎn) 50個(gè)
for (int i = 0; i 50; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//畫圖片的邊框線
g.DrawRectangle(new Pen(Color.Peru), 0, 0, image.Width - 1, image.Height - 1);
//創(chuàng)建內(nèi)存流用于輸出圖片
using (MemoryStream ms = new MemoryStream())
{
//圖片格式指定為png
image.Save(ms, ImageFormat.Jpeg);
//清除緩沖區(qū)流中的所有輸出
System.Web.HttpContext.Current.Response.ClearContent();
//輸出流的HTTP MIME類型設(shè)置為"image/Png"
System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";
//輸出圖片的二進(jìn)制流
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
}
finally
{
//釋放Bitmap對(duì)象和Graphics對(duì)象
g.Dispose();
image.Dispose();
}
}