實現代碼
/// <summary> /// 產生驗證碼圖片,儲存session名稱VerificationCode /// </summary> public static void CreateVerificationCode() { int number; string checkCode = string.Empty; //隨機數種子 Random randoms = new Random(); for (int i = 0; i < 4; i++) //校正碼長度為4 { //隨機的整數 number = randoms.Next(); //字元從0-9,A-Z中隨機產生,對應的ASCII碼分別為 //48-57,65-90 number = number % 36; if (number < 10) { number += 48; } else { number += 55; } checkCode += ((char)number).ToString(); } //在session中儲存校正碼 System.Web.HttpContext.Current.Session["VerificationCode"] = checkCode; //若校正碼為空白,則直接返回 if (checkCode == null || checkCode.Trim() == String.Empty) { return; } //根據校正碼的長度確定輸出圖片的長度 System.Drawing.Bitmap image = new System.Drawing.Bitmap(55, 20);//(int)Math.Ceiling(Convert.ToDouble(checkCode.Length * 15)) //建立Graphics對象 Graphics g = Graphics.FromImage(image); try { //產生隨機數種子 Random random = new Random(); //清空圖片背景色 g.Clear(Color.White); //畫圖片的背景雜音線 10條 //--------------------------------------------------- for (int i = 0; i < 10; i++) { //噪音線起點座標(x1,y1),終點座標(x2,y2) 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); } //--------------------------------------------------- //Brush b = Brushes.Silver; //g.FillRectangle(b, 0, 0, image.Width, image.Height); //---------------------以上兩種任選其一------------------------------ //輸出圖片中校正碼的字型: 12號Arial,粗斜體 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); //線性漸層畫刷 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Purple, 1.2f, true); g.DrawString(checkCode, font, brush, 2, 2); //畫圖片的前景噪音點 50個 for (int i = 0; i < 50; 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.Peru), 0, 0, image.Width - 1, image.Height - 1); //建立記憶體流用於輸出圖片 using (MemoryStream ms = new MemoryStream()) { //圖片格式指定為png image.Save(ms, ImageFormat.Jpeg); //清除緩衝區流中的所有輸出 System.Web.HttpContext.Current.Response.ClearContent(); //輸出資料流的HTTP MIME類型設定為"image/Png" System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg"; //輸出圖片的二進位流 System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); } } finally { //釋放Bitmap對象和Graphics對象 g.Dispose(); image.Dispose(); } }
建立一個aspx頁面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AuthCode.aspx.cs" Inherits="AuthCode" %> <%Help.CreateVerificationCode(); %>
添加HTML代碼,引用
<div class="positionR"> <label>驗證碼:</label> <span class="style1"> *</span> <input type="text" class="yanZm" runat="Server" reg="^.+$" id="txtAuthCode" tip="請輸入驗證碼!" /> <img class="yanZm_img" src="AuthCode.aspx" alt="" id="imgAuthCode" /> </div>
如何?重新整理?
<script type="text/javascript"> $("#imgAuthCode").click(function () { $(this).attr("src", "AuthCode.aspx?code=" + (new Date()).getTime()); }); </script>