把下面代码存为一个文件code.aspx。另一个文件里调用<img src="code.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;
public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
getimg(getcode(4));
}
}
public string getcode(int num)
{
string[] source ={ "1", "A", "B", "4", "C", "6", "7", "8", "9", "Q", "W", "Y", "U", "O", "P" };
//string[] source ={ "A", "B", "C", "Q", "W", "Y", "U", "O", "P" };
string code = "";
Random rm = new Random();
for(int i = 0; i < num; i++)
{
code += source[rm.Next(0, source.Length)];
}
return code;
}
public void getimg(string code)
{
Bitmap myPalette = new Bitmap(60, 20);
Graphics gh = Graphics.FromImage(myPalette);
Rectangle rc = new Rectangle(0, 0, 60, 20);
gh.FillRectangle(new SolidBrush(Color.Silver), rc);
gh.DrawString(code, new Font("宋体", 16), new SolidBrush(Color.Gray), rc);
myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Session["ValidataCode"] = code;
gh.Dispose();
myPalette.Dispose();
}
}