http://www.cnblogs.com/jianjialin/archive/2009/02/05.html
驗證碼 aspx
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
//該源碼下載自www.51aspx.com(51aspx.com)
namespace ComplexValide
{
public partial class ValidCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Random rd = new Random(); //建立隨機數對象
//以下4行,產生由6個字母和數字組成的一個字串
string str = "ABCDEFGHIJKLMNOPQRSTURWXYZ0123456789";
string my51aspx = "";
for (int i = 0; i < 6; i++)
{
my51aspx = my51aspx + str.Substring(rd.Next(36), 1);
}
//驗證碼值存放到Session中用來比較
Session["Valid"] = my51aspx;
//以下三句,通過隨機找一個現有圖象產生一個畫布Bitmap
string bgFilePath = Server.MapPath(".\\images\\bg" + new Random().Next(5) + ".jpg");//隨機找個圖象
System.Drawing.Image imgObj = System.Drawing.Image.FromFile(bgFilePath);
Bitmap newBitmap = new Bitmap(imgObj, 290, 80);//建立位元影像對象
Graphics g = Graphics.FromImage(newBitmap);//根據上面建立的位元影像對象建立繪圖面
SolidBrush brush = new SolidBrush(Color.Black);//設定畫筆顏色
//定義一個含10種字型的數組
String[] fontFamily ={ "Arial", "Verdana", "Comic Sans MS", "Impact", "Haettenschweiler", "Lucida Sans Unicode", "Garamond", "Courier New", "Book Antiqua", "Arial Narrow" };
//通過迴圈,繪製每個字元,
for (int a = 0; a < my51aspx.Length; a++)
{
Font textFont = new Font(fontFamily[rd.Next(9)], 30, FontStyle.Bold);//字型隨機,字型大小大小30,加粗
//每次迴圈繪製一個字元,設定字型格式,畫筆顏色,字元相對畫布的X座標,字元相對畫布的Y座標
g.DrawString(my51aspx.Substring(a, 1), textFont, brush, 40 + a * 36, 20);
}
//儲存畫的圖片到輸出資料流中
newBitmap.Save(Response.OutputStream, ImageFormat.Gif);
}
}
}
qiantai
<script type="text/javascript">
function ShowValidImage() {
var numkey = Math.random();
document.getElementById("imgRandom").src = "/ValidCode.aspx?NumKey="+numkey;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img id="imgRandom" alt="看不清?點擊更換" onclick="ShowValidImage()" src="/ValidCode.aspx?" title="看不清?點擊更換" />
</div>
</form>
</body>