欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

后台生产验证码code和byte[]图片

程序员文章站 2022-04-04 18:07:43
引用命名空间 using System.Drawing;using System.Drawing.Drawing2D;using System.Drawing.Imaging;using System.IO; 生成方法 /// 生成验证码 /// ///

引用命名空间

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

 

 

生成方法

/// <summary>生成验证码
/// </summary>
/// <returns></returns>
public string GetCheckCode()
{
int number;
char code;
string checkCode = String.Empty;

System.Random random = new Random();
do
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
if (code == 'o' || code == 'O') continue;
checkCode += code.ToString();
} while (checkCode.Length < 4);
//code储存.在session
KMHC.Infrastructure.SessionHelper.SetSession("checkCode", checkCode.ToUpper());

byte[] bytes = CreateValidateGraphic(checkCode.ToLower());
var response = new BaseResponse<string>();
var src = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);//Base64转换 HTML标签img 直接显示 <img src="" />
return src;
}


/// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="containsPage"></param>
/// <param name="validateNum"></param>
public static byte[] CreateValidateGraphic(string checkCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(checkCode.Length * 13.5), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; 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 font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, brush, 3, 2);
//画图片的前景干扰点
for (int i = 0; i < 100; 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);
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片

return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}