protected void Page_Load(object sender, EventArgs e)
{
string str = "0123456789";
char[] chs = str.ToCharArray();
Random rand = new Random();
string validater = "";
for (int i = 0; i < 4; i++)
{
char x = chs[rand.Next(0, chs.Length)];
validater += x;
}
Session["validater_code"] = validater;
//Response.Write(validater);
CreateImage(validater);
}
protected void CreateImage(string str)
{
int iWidth = str.Length * 11;
Bitmap img = new Bitmap(iWidth,20);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.White);
Color[] colors = new Color[] {Color.White,Color.Red,Color.Yellow,Color.Black,Color.Blue};
Random rand = new Random();
for (int i = 0; i < str.Length; i++)
{
Color c=colors[rand.Next(0,colors.Length)];
Font f = new Font("Courier New",11);
Brush b = new System.Drawing.SolidBrush(c);
g.DrawString(str.Substring(i, 1), f, b, (i * 10) + 1, 1, StringFormat.GenericDefault);
}
//描边
g.DrawRectangle(new Pen(Color.Black), 0, 0, img.Width - 1, img.Height - 1); ;
//保存图片到内存
MemoryStream ms = new MemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
//页面的东西全部清除 只剩下面的图片
Response.Clear();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
img.Dispose();
}