C# 驗證碼操作
public partial class 驗證碼 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//產生隨機數
string tmp = RndNum(5).ToUpper();
//用session進行傳值
this.Session["ImageV"] = tmp;
//生產圖片
this.CreateCheckCodeImage(tmp);
}
//生驗證碼隨即數字+字母組合
private string RndNum(int VcodeNum)
string Vchar = "a,b,c,d,e,0,1,2,3,4,5,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,0,1,2,3,4,5,6,7,8,9,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,n,o,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(35);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
//創建驗證碼背景圖片
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 13.0)), 21);
Graphics g = Graphics.FromImage(image);
try
//生成隨機生成器
Random random = new Random();
//清空圖片背景色
g.Clear(Color.White);
//畫圖片的背景噪音線
for (int i = 0; i < 25; 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.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
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, 1);
//畫圖片的前景噪音點
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";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
在第二個頁面裏拖放一個圖片控件,設置一下圖片的Url地址,就可以在第二個頁面顯示出驗證碼了。
<asp:Image ID="Image1" runat="server" Height="40px" ImageUrl="~/Default.aspx" Width="70px" />