using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing; dom
public partial class ValidateCode : System.Web.UI.Page
{
Random rd = new Random();
protected void Page_Load(object sender, EventArgs e)
{
Session["ValidateCode"] = getRandomCode();
getCheckCodeImage(getRandomCode());
} ide
public string getRandomCode() //生成隨機碼
{ spa
int num;
char code;
string checkcode = String.Empty;
for (int i = 1; i <= 5; i++)
{
num = rd.Next();
if (num % 2 == 0)
code = (char)('0' + (char)(num % 10));
else
code = (char)('A' + (char)(num % 26)); code
checkcode += code.ToString();
}
return checkcode;
} orm
public void getCheckCodeImage(string checkCode) //生成圖像
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return; server
Bitmap bmp = new System.Drawing.Bitmap(100, 40);
Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.Clear(Color.White); 圖片
for (int i = 0; i < 10; i++) //畫噪線
{
int x1 = rd.Next(bmp.Width);
int y1 = rd.Next(bmp.Height);
int x2 = rd.Next(bmp.Width);
int y2 = rd.Next(bmp.Height);
g.DrawLine(new Pen(Color.FromArgb(rd.Next())), x1, y1, x2, y2);
} get
for (int i = 0; i < 100; i++) //畫噪點
{
int x = rd.Next(bmp.Width);
int y = rd.Next(bmp.Height);
bmp.SetPixel(x, y, Color.FromArgb(rd.Next()));
}
Font font = new System.Drawing.Font("Book Antiqua", 20, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
SolidBrush brush = new SolidBrush(Color.Black);
g.DrawString(checkCode, font, brush, 0.7f, 4); string
//畫圖像的邊框
g.DrawRectangle(new Pen(Color.Red), 0, 0, bmp.Width - 1, bmp.Height - 1); it
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "p_w_picpath/Gif";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
bmp.Dispose();
}
用的時候只需添加一個圖片控件,而且把圖片控件的地址,設置爲本cs代碼的前臺頁面地址便可,例如:<asp:ImageButton ID="ImageButton1" runat="server" Height="40px"
ImageUrl="~/ValidateCode.aspx" Width="100px" />