using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
protected void Page_Load(object sender, EventArgs e)
{
string str_ValidateCode = GetRandomNumberString(5);
Session["ValidateCode"] = str_ValidateCode; //驗證號碼存入session
CreateCheckCodeImage(str_ValidateCode);
}
//亂數產生數字
private string GetRandomNumberString(int int_NumberLength)
{
Random rnd = new Random();
string RandonStr = "";
for (int i = 0; i < int_NumberLength; i++)
{
RandonStr += rnd.Next(1, 9).ToString();
}
return RandonStr;
}
//動態建立圖片
private void CreateCheckCodeImage(string checkCode)
{
Bitmap image = new Bitmap((int)(Math.Ceiling((checkCode.Length * 13.5))) , 25);
Graphics g = Graphics.FromImage(image);
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", 14, (FontStyle.Bold));
var 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()));
}
string savePath = Server.MapPath("~") + "/images/validate.gif"; //圖片存放位子
image.Save(savePath, System.Drawing.Imaging.ImageFormat.Gif);
}
標籤: C#