热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

后台生产验证码code和byte[]图片引用命名空间usingSystem.Drawing;usingSystem.Drawing.Drawing2D;usingSystem.Dr

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

引用命名空间

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

 

 

生成方法

///

生成验证码
///

///
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 &#61; CreateValidateGraphic(checkCode.ToLower());
var response &#61; new BaseResponse();
var src &#61; "data:image/jpeg;base64," &#43; Convert.ToBase64String(bytes);//Base64转换 HTML标签img 直接显示
return src;
}


///


/// 创建验证码的图片
///

///
///
public static byte[] CreateValidateGraphic(string checkCode)
{
Bitmap image &#61; new Bitmap((int)Math.Ceiling(checkCode.Length * 13.5), 22);
Graphics g &#61; Graphics.FromImage(image);
try
{
//生成随机生成器 
Random random &#61; new Random();
//清空图片背景色 
g.Clear(Color.White);
//画图片的干扰线 
for (int i &#61; 0; i <25; i&#43;&#43;)
{
int x1 &#61; random.Next(image.Width); int x2 &#61; random.Next(image.Width);
int y1 &#61; random.Next(image.Height);
int y2 &#61; random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font &#61; new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush &#61; 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 &#61; 0; i <100; i&#43;&#43;)
{
int x &#61; random.Next(image.Width); int y &#61; 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 &#61; new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片

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




推荐阅读
author-avatar
紫百合1990_950
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有