調用
驗證碼:<input type="text" id="txtValidate" style="border: solid 1px #9B9B9B; width: 85px; height: 17px;" /> <img src="Rnd.aspx" mce_src="Rnd.aspx" style="width: 58px; height: 17px; border: solid 1px #9B9B9B" align="absmiddle" />
後台實現
Rnd.aspx.cs
using System;using System.Collections;using System.Configuration;using System.Data;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Drawing;using System.Drawing.Imaging;public partial class Rnd : System.Web.UI.Page{ private int codeLen = 5;//隨機顯示字元個數 private int fineness = 100;//圖片清晰度 private int imgWidth = 65;//圖片寬度 private int imgHeight = 20;//圖片高度 private string fontFamily = "Roman";//字型名稱 private int fontSize = 12; //字型大小 private Random random = new Random(); protected void Page_Load(object sender, EventArgs e) { string validateCode = CreateValidateCode(); Session["RandomNumber"] = validateCode; Bitmap bitmap = new Bitmap(imgWidth, imgHeight); DisturbBitmap(bitmap); DrawValidateCode(bitmap, validateCode); bitmap.Save(Response.OutputStream, ImageFormat.Gif); } private string CreateValidateCode()//得到隨機數 { string validateCode = ""; for (int i = 0; i < codeLen; i++) { int n = random.Next(10);//返回一個小於最大值得隨機數 validateCode += n.ToString(); } return validateCode; } private void DisturbBitmap(Bitmap bitmap)//擷取背景圖 { for (int i = 0; i < bitmap.Width; i++) { for (int j = 0; j < bitmap.Height; j++) { if (random.Next(90) <= this.fineness) { bitmap.SetPixel(i, j, Color.White);//擷取指定位置的像素顏色 } } } } private void DrawValidateCode(Bitmap bitmap, string validateCode) { Graphics g = Graphics.FromImage(bitmap); Font font = new Font(fontFamily, fontSize, FontStyle.Bold); g.DrawString(validateCode, font, Brushes.Green, random.Next(-3, 11), random.Next(-4, 1));//在指定地區繪製文本字元 }}