調(diào)用驗(yàn)證碼:
<tr>
<td>驗(yàn)證碼:</td>
<td class="style2">
<asp:TextBox ID="TextBox3" runat="server" Width="77px"></asp:TextBox>
</td>
<td>
<asp:Image ID="Image1" runat="server" style="margin-left: 0px; cursor:pointer" Width="51px " Height="23px" ImageUrl="Yzm.aspx" ToolTip="不分大小寫,點(diǎn)擊刷新" onclick="this.src='Yzm.aspx?'+Math.random()" />
</td>
</tr>
Yzm.aspx中
using System.Drawing;
protected void Page_Load(object sender, EventArgs e)
{
string checkCode = CreateRandomCode(4);
Session["CheckCode"] = checkCode;
CreateImage(checkCode);
}
//產(chǎn)生4個(gè)隨即字符
private string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(','); //以","為分割符把allChar拆分成數(shù)據(jù);
string randomCode = "";
int temp;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
int t = rand.Next(35);
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
//給隨即字符添加干擾
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 11.5);
//封裝 GDI+ 位圖,此位圖由圖形圖像及其屬性的像素?cái)?shù)據(jù)組成 .指定寬度和高度。以象素為單位
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
//封裝一個(gè) GDI+ 繪圖圖面。無(wú)法繼承此類. 從指定的 Image 創(chuàng)建新的 Graphics
Graphics g = Graphics.FromImage(image);
//font封裝在特定設(shè)備上呈現(xiàn)特定字體所需的紋理和資源 (字體,大小,字體樣式)
Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
/**Brush定義用于填充圖形形狀(如矩形、橢圓、餅形、多邊形和封閉路徑)的內(nèi)部的對(duì)象
SolidBrush(Color.White)初始化指定顏色 指定畫(huà)筆顏色為白色**/
Brush b = new System.Drawing.SolidBrush(Color.Yellow);
//清除整個(gè)繪圖面并以指定背景色填充
g.Clear(Color.Firebrick);
/**在指定位置并且用指定的 Brush 和 Font 對(duì)象繪制指定的文本字符串
(指定的字符串,字符串的文本格式,繪制文本的顏色和紋理,所繪制文本的左上角的 x 坐標(biāo),坐標(biāo))**/
g.DrawString(checkCode, f, b, 3, 3);
//定義用于繪制直線和曲線的對(duì)象。(指示此 Pen 的顏色,指示此 Pen 的寬度的值)
Pen blackPen = new Pen(Color.Red, 0);
Random rand = new Random();
for (int i = 0; i < 3; i++)
{
//隨即高度
int y = rand.Next(image.Height);
//繪制一條連接由坐標(biāo)對(duì)指定的兩個(gè)點(diǎn)的線條
//(線條的顏色、寬度和樣式,第一個(gè)點(diǎn)的 x 坐標(biāo),第一個(gè)點(diǎn)的 y 坐標(biāo),第二個(gè)點(diǎn)的 x 坐標(biāo),第二個(gè)點(diǎn)的 y 坐標(biāo))
g.DrawLine(blackPen, 0, y, image.Width, y);
}
//創(chuàng)建存儲(chǔ)區(qū)為內(nèi)存的流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//將此圖像以指定的格式保存到指定的流中(將其保存在內(nèi)存流中,圖像的格式)
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//清除緩沖區(qū)將流中的內(nèi)容輸出
Response.ClearContent();
//獲取輸出流的類型
Response.ContentType = "image/Jpeg";
//將二進(jìn)制字符串寫入HTTP輸出流
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
聯(lián)系客服