using System.Drawing;
using System.Drawing.Imaging;
protected void Page_Load(object sender, EventArgs e)
{
Bitmap bitmap = CreateBitmap(GetRandomDigit(2) + GetRandomNumbers(2));
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
bitmap.Dispose();
}
#region 数字验证
public string GetRandomDigit(int len)
{
string str = "1234567890";
string strResult = "";
Random random = new Random(unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < len; i++)
{
strResult += str[random.Next(0, 10)].ToString();
}
return strResult;
}
#endregion
#region 字母验证
public string GetRandomNumbers(int len)
{
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String strResult = "";
Random random = new Random();
for (int i = 0; i < len; i++)
{
strResult += str[random.Next(0, 10)].ToString();
}
return strResult;
}
#endregion
public Bitmap CreateBitmap(string check)
{
int width = (int)(check.Length * 12);
Bitmap bitmap = new Bitmap(width, 20);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan, Color.Purple };
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
Random random = new Random();
for (int i = 0; i < 30; i++)
{
int x1 = random.Next(bitmap.Width);
int x2 = random.Next(bitmap.Width);
int y1 = random.Next(bitmap.Height);
int y2 = random.Next(bitmap.Height);
graphics.DrawLine(new Pen(Color.LightGray, 1), new Point(x1, y1), new Point(x2, y2));
}
for (int i = 0; i < check.Length; i++)
{
int cIndex = random.Next(c.Length - 1);
int fIndex = random.Next(font.Length);
Font f = new Font(font[fIndex].ToString(), 10, FontStyle.Regular);
Brush b = new SolidBrush(c[cIndex]);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
graphics.DrawString(check.Substring(i, 1), f, b, new PointF(3 + (i * 12), ii));
}
graphics.Flush();
return bitmap;
}
}
前台: <img src="Default.aspx" οnclick="this.src=this.src+'?'" alt="验证码" />