using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateCheckCodeImage(GenerateCheckCode());
}
}
// 產生四位隨機數的方法
private string GenerateCheckCode()
{
int number;
char code;
//表示字符串爲空,次字段爲只讀
string checkCode = string.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
code = (char)('0' + (char)(number % 10));
checkCode += code.ToString();
}
//將驗證碼保存到cookie中
Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
//當隨機數是空的時候或者 去掉空格還是空的時候
if (checkCode == null || checkCode.Trim() == string.Empty)
return;
// 創建位圖 4 * 12.5
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成隨機生成器
Random random = new Random();
//清空圖片背景色
g.Clear(Color.White);
//畫圖片的畢竟噪音線
for (int i = 0; i < 2; i++)
{
//產生隨機的起始座標和重點座標
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.Black), x1, y1, x2, y2);
}
//字體 大小12 加粗
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
// 線性漸變封裝
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
// 畫圖片的前景噪點
for (int i = 0; i < 100; 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.Silver), 0, 0, image.Width - 1, image.Height - 1);
//創建其支持存儲區爲內存的
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
// 清楚緩衝區流中的所有內容輸出
Response.ClearContent();
// 獲取或設置輸出流的格式
Response.ContentType = "image/gif";
//將一個二進制字符串 寫入輸出流 ms.ToArray()將整個流內容寫入數組
Response.BinaryWrite(ms.ToArray());
}
finally
{
// 釋放資源
g.Dispose();
image.Dispose();
}
}
}
展示的頁面:驗證碼用HTML標籤ima表示的 src的路徑制定到Code.aspx
當點擊圖片的時候自動的刷新圖片的路徑 達到更換驗證碼的目的.。是通過js刷新img的src的路徑實現的
<img id="Img1" alt="看不清,請點擊我!" οnclick="this.src=this.src+'?'" src="Code.aspx" style="width: 73px; height: 22px" align="left" />
驗證頁面的後臺代碼:
protected void Button1_Click(object sender, EventArgs e)
{
string code = this.txtCode.Text;
//從cookie中取出驗證碼
HttpCookie cookie = Request.Cookies["CheckCode"];
if (code == cookie.Value.ToString())
{
Response.Write("正確");
}
else
{
Response.Write("錯誤");
}
}
將驗證碼保存到cookie中:Response.Cookies.Add(new HttpCookie("CheckCode",checkCode));從 cookie中取出驗證碼:HttpCookie cookie = Request.Cookies["CheckCode"];