http://www.cnblogs.com/jianjialin/archive/2009/02/05.html
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);
}
}
}
<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>