自己寫了一個驗證碼圖片生成的頁面
效果如下:
主要實現效果
- 隨機漸變背景
- 隨機字體顏色(漸變)、大小、角度、扭曲
- 隨機干擾曲線
代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
//設置不緩存此頁
Response.AppendHeader("pragma", "no-cache");
Response.AppendHeader("Cache-Control", "no-cache, must-revalidate");
Response.AppendHeader("expires", "0");
Random rand = new Random();
//獲取隨機字符
string str = GetRandString(4);
//創建畫板
Bitmap image = new Bitmap(80, 26);
Graphics g = Graphics.FromImage(image);
//g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.InterpolationMode = InterpolationMode.Low;
//g.CompositingMode = CompositingMode.SourceOver;
//g.CompositingQuality = CompositingQuality.HighQuality;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.SmoothingMode = SmoothingMode.AntiAlias;
//繪制漸變背景
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
Brush brushBack = new LinearGradientBrush(rect, Color.FromArgb(rand.Next(150, 256), 255, 255), Color.FromArgb(255, rand.Next(150, 256), 255), rand.Next(90));
g.FillRectangle(brushBack, rect);
//繪制干擾曲線
for (int i = 0; i < 2; i++)
{
Point p1 = new Point(0, rand.Next(image.Height));
Point p2 = new Point(rand.Next(image.Width), rand.Next(image.Height));
Point p3 = new Point(rand.Next(image.Width), rand.Next(image.Height));
Point p4 = new Point(image.Width, rand.Next(image.Height));
Point[] p = { p1, p2, p3, p4 };
Pen pen = new Pen(Color.Gray, 1);
g.DrawBeziers(pen, p);
}
//逐個繪制文字
for (int i = 0; i < str.Length; i++)
{
string strChar = str.Substring(i, 1);
int deg = rand.Next(-15, 15);
float x = (image.Width / str.Length / 2) + (image.Width / str.Length) * i;
float y = image.Height / 2;
//隨機字體大小
Font font = new Font("Consolas", rand.Next(16, 24), FontStyle.Regular);
SizeF size = g.MeasureString(strChar, font);
Matrix m = new Matrix();
//旋轉
m.RotateAt(deg, new PointF(x, y), MatrixOrder.Append);
//扭曲
m.Shear(rand.Next(-10, 10) * 0.03f, 0);
g.Transform = m;
//隨機漸變畫筆
Brush brushPen = new LinearGradientBrush(rect, Color.FromArgb(rand.Next(0, 256), 0, 0), Color.FromArgb(0, 0, rand.Next(0, 256)), rand.Next(90));
g.DrawString(str.Substring(i, 1), font, brushPen, new PointF(x - size.Width / 2, y - size.Height / 2));
g.Transform = new Matrix();
}
g.Save();
Response.ContentType = "image/jpeg";
Response.Clear();
Response.BufferOutput = true;
image.Save(Response.OutputStream, ImageFormat.Jpeg);
g.Dispose();
image.Dispose();
Response.Flush();
}
//獲取隨機數
private string GetRandString(int len)
{
//string s = "0123456789";
string s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string str = "";
Random r = new Random();
for (int i = 0; i < len; i++)
{
str += s.Substring(r.Next(s.Length), 1);
}
return str;
}