需要自己创建一个项目
代码如下
#region 验证码
public static class ValidateCode
{
public static string CreateValidateCode(int length)
{
string ch = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ1234567890@#$%&?";
byte[] b = new byte[4];
using var cpt = new RNGCryptoServiceProvider();
cpt.GetBytes(b);
var r = new Random(BitConverter.ToInt32(b, 0));
var sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append(ch[r.Next(ch.Length)]);
}
return sb.ToString();
}
public static byte[] CreateValidateGraphic(this HttpContext context, string validateCode, int fontSize = 22, int lineHeight = 36)
{
using Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * (fontSize + 2.0)), lineHeight);
using Graphics g = Graphics.FromImage(image);
Random random = new Random();
g.Clear(Color.White);
for (int i = 0; i < 75; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font[] fonts =
{
new Font("Arial", fontSize, FontStyle.Bold | FontStyle.Italic),
new Font("微软雅黑", fontSize, FontStyle.Bold | FontStyle.Italic),
new Font("黑体", fontSize, FontStyle.Bold | FontStyle.Italic),
new Font("宋体", fontSize, FontStyle.Bold | FontStyle.Italic),
new Font("楷体", fontSize, FontStyle.Bold | FontStyle.Italic)
};
using var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, fonts[new Random().Next(fonts.Length)], brush, 3, 2);
for (int i = 0; i < 300; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
using MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
return stream.ToArray();
}
}
#endregion
