您好,登錄后才能下訂單哦!
這篇文章給大家介紹如何進行網站驗證碼制作,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
asp.net驗證碼制作
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class yzm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string chkCode = string.Empty;
//顏色列表,用于驗證碼、噪線、噪點
Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
//字體列表,用于驗證碼
string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
//驗證碼的字符集,去掉了一些容易混淆的字符
char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new Random();
//生成驗證碼字符串
for (int i = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
//用session對象存儲驗證碼
Session["name"] = chkCode;
Bitmap bmp = new Bitmap(100, 40);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
//畫噪線
for (int i = 0; i < 10; i++)
{
int x1 = rnd.Next(100);
int y1 = rnd.Next(40);
int x2 = rnd.Next(100);
int y2 = rnd.Next(40);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//畫驗證碼字符串
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, 18);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8);
}
//畫噪點
for (int i = 0; i < 100; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}
//清除該頁輸出緩存,設置該頁無緩存
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
//將驗證碼圖片寫入內存流,并將其以 "p_w_picpath/Png" 格式輸出
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "p_w_picpath/Png";
Response.BinaryWrite(ms.ToArray());
}
finally
{
//顯式釋放資源
bmp.Dispose();
g.Dispose();
}
}
}
}
關于如何進行網站驗證碼制作就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。