很多人写的博客大家看了会一知半解,不知道怎么用,应该引用什么类库或者代码不全,这样很多小白很是头疼,尤其是尝新技术更是如此。我们这边不止告诉你步骤,而且还提供开源demo。随着时间的推移,我们的demo库会日益强大请及时收藏GitHub

1.首先你需要Nuget引用类库

Install-Package ZKWeb.System.Drawing -Version 4.0.

2.创建公共类VerifyCodeHelper和CommonHelper

(1)CommonHelper中添加图形处理方法

#region 验证码
public static byte[] Bitmap2Byte(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
byte[] data = new byte[stream.Length];
stream.Seek(, SeekOrigin.Begin);
stream.Read(data, , Convert.ToInt32(stream.Length));
return data;
}
}
#endregion
public static string CodeJson(string code, string msg)
{
return "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\"}";
}

(2)VerifyCodeHelper添加图形处理方法

public  class VerifyCodeHelper
{
#region 单例模式
//创建私有化静态obj锁
private static readonly object _ObjLock = new object();
//创建私有静态字段,接收类的实例化对象
private static VerifyCodeHelper _VerifyCodeHelper = null;
//构造函数私有化
private VerifyCodeHelper() { }
//创建单利对象资源并返回
public static VerifyCodeHelper GetSingleObj()
{
if (_VerifyCodeHelper == null)
{
lock (_ObjLock)
{
if (_VerifyCodeHelper == null)
_VerifyCodeHelper = new VerifyCodeHelper();
}
}
return _VerifyCodeHelper;
}
#endregion #region 生产验证码
public enum VerifyCodeType { NumberVerifyCode, AbcVerifyCode, MixVerifyCode }; /// <summary>
/// 1.数字验证码
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
private string CreateNumberVerifyCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = seekRand.Next(, Int32.MaxValue - length * );
int[] seeks = new int[length];
for (int i = ; i < length; i++)
{
beginSeek += ;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = ; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = * (int)Math.Pow(, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = ; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(, numLength - );
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, ));
}
//生成验证码
for (int i = ; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
} /// <summary>
/// 2.字母验证码
/// </summary>
/// <param name="length">字符长度</param>
/// <returns>验证码字符</returns>
private string CreateAbcVerifyCode(int length)
{
char[] verification = new char[length];
char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
Random random = new Random();
for (int i = ; i < length; i++)
{
verification[i] = dictionary[random.Next(dictionary.Length - )];
}
return new string(verification);
} /// <summary>
/// 3.混合验证码
/// </summary>
/// <param name="length">字符长度</param>
/// <returns>验证码字符</returns>
private string CreateMixVerifyCode(int length)
{
char[] verification = new char[length];
char[] dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'', '', '', '', '', '', '', '', '', '',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
Random random = new Random();
for (int i = ; i < length; i++)
{
verification[i] = dictionary[random.Next(dictionary.Length - )];
}
return new string(verification);
} /// <summary>
/// 产生验证码(随机产生4-6位)
/// </summary>
/// <param name="type">验证码类型:数字,字符,符合</param>
/// <returns></returns>
public string CreateVerifyCode(VerifyCodeType type)
{
string verifyCode = string.Empty;
Random random = new Random();
int length = random.Next(, );
switch (type)
{
case VerifyCodeType.NumberVerifyCode:
verifyCode = GetSingleObj().CreateNumberVerifyCode(length);
break;
case VerifyCodeType.AbcVerifyCode:
verifyCode = GetSingleObj().CreateAbcVerifyCode(length);
break;
case VerifyCodeType.MixVerifyCode:
verifyCode = GetSingleObj().CreateMixVerifyCode(length);
break;
}
return verifyCode;
}
#endregion #region 验证码图片
/// <summary>
/// 验证码图片 => Bitmap
/// </summary>
/// <param name="verifyCode">验证码</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <returns>Bitmap</returns>
public Bitmap CreateBitmapByImgVerifyCode(string verifyCode, int width, int height)
{
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
Brush brush;
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
SizeF totalSizeF = g.MeasureString(verifyCode, font);
SizeF curCharSizeF;
PointF startPointF = new PointF(, (height - totalSizeF.Height) / );
Random random = new Random(); //随机数产生器
g.Clear(Color.White); //清空图片背景色
for (int i = ; i < verifyCode.Length; i++)
{
brush = new LinearGradientBrush(new Point(, ), new Point(, ), Color.FromArgb(random.Next(), random.Next(), random.Next()), Color.FromArgb(random.Next(), random.Next(), random.Next()));
g.DrawString(verifyCode[i].ToString(), font, brush, startPointF);
curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font);
startPointF.X += curCharSizeF.Width;
} //画图片的干扰线
for (int i = ; i < ; 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);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} //画图片的前景干扰点
for (int i = ; i < ; i++)
{
int x = random.Next(bitmap.Width);
int y = random.Next(bitmap.Height);
bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
} g.DrawRectangle(new Pen(Color.Silver), , , bitmap.Width - , bitmap.Height - ); //画图片的边框线
g.Dispose();
return bitmap;
} /// <summary>
/// 验证码图片 => byte[]
/// </summary>
/// <param name="verifyCode">验证码</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <returns>byte[]</returns>
public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height)
{
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
Brush brush;
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
SizeF totalSizeF = g.MeasureString(verifyCode, font);
SizeF curCharSizeF;
PointF startPointF = new PointF(, (height - totalSizeF.Height) / );
Random random = new Random(); //随机数产生器
g.Clear(Color.White); //清空图片背景色
for (int i = ; i < verifyCode.Length; i++)
{
brush = new LinearGradientBrush(new Point(, ), new Point(, ), Color.FromArgb(random.Next(), random.Next(), random.Next()), Color.FromArgb(random.Next(), random.Next(), random.Next()));
g.DrawString(verifyCode[i].ToString(), font, brush, startPointF);
curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font);
startPointF.X += curCharSizeF.Width;
} //画图片的干扰线
for (int i = ; i < ; 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);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} //画图片的前景干扰点
for (int i = ; i < ; i++)
{
int x = random.Next(bitmap.Width);
int y = random.Next(bitmap.Height);
bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
} g.DrawRectangle(new Pen(Color.Silver), , , bitmap.Width - , bitmap.Height - ); //画图片的边框线
g.Dispose(); //保存图片数据
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray(); }
#endregion

3.后台控制器根据请求返回相应图形数据

 #region 验证码

        #region 混合验证码

        [HttpGet]
public string MixVerifyCodeJson()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
string uuid = Guid.NewGuid().ToString();
return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
}
[HttpGet]
public IActionResult MixVerifyCode()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);
return File(stream.ToArray(), "image/png");
}
#endregion #region 数字验证码
[HttpGet]
public string NumberVerifyCodeJson()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
string uuid = Guid.NewGuid().ToString();
return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
}
[HttpGet]
public IActionResult NumberVerifyCode()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);
return File(stream.ToArray(), "image/png");
}
#endregion #region 字母验证码
[HttpGet]
public IActionResult AbcVerifyCode()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);
return File(stream.ToArray(), "image/png");
}
[HttpGet]
public string AbcVerifyCodeJson()
{
string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode);
var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, , );
byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
string uuid = Guid.NewGuid().ToString();
return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
}
#endregion #endregion

4.前端请求分为直接请求文件或json图形数据并渲染至Img标签

<script type="text/javascript">
$(function () {
refreshNumJson();
refreshMixJson();
refreshAbcJson();
});
function refreshNum() {
var id = document.getElementById("numImg");
var str = "/Verify/NumberVerifyCode?random=" + Math.random();
id.setAttribute("src", str);
}
function refreshNumJson() {
$.ajax({
type: "get",
contentType: 'application/json',
url: '/Verify/NumberVerifyCodeJson?' + Math.random(),
dataType: 'json',
async: false,
success: function (data) {
$("#numImgJson").attr("src", "data:image/png;base64," + data.msg);
console.log(data.code);
},
error: function (xhr) {
console.log(xhr.responseText);
}
});
} function refreshMix() {
var id = document.getElementById("mixImg");
var str = "/Verify/MixVerifyCode?random=" + Math.random();
id.setAttribute("src", str);
}
function refreshMixJson() {
$.ajax({
type: "get",
contentType: 'application/json',
url: '/Verify/MixVerifyCodeJson?' + Math.random(),
dataType: 'json',
async: false,
success: function (data) {
$("#mixImgJson").attr("src", "data:image/png;base64," + data.msg);
console.log(data.code);
},
error: function (xhr) {
console.log(xhr.responseText);
}
});
} function refreshAbc() {
var id = document.getElementById("abcImg");
var str = "/Verify/AbcVerifyCode?random=" + Math.random();
id.setAttribute("src", str);
}
function refreshAbcJson() {
$.ajax({
type: "get",
contentType: 'application/json',
url: '/Verify/AbcVerifyCodeJson?' + Math.random(),
dataType: 'json',
async: false,
success: function (data) {
$("#abcImgJson").attr("src", "data:image/png;base64," + data.msg);
console.log(data.code);
},
error: function (xhr) {
console.log(xhr.responseText);
}
});
}
</script> <h2>图形数字验证码</h2>
<img id="numImgJson" title="数字验证码Json获取"
alt="vcode" style="cursor:pointer;" onclick="refreshNumJson()" />
<a href="javascript:void(0);" onclick="refreshNumJson()">看不清,换一张</a>
<img id="numImg" title="数字验证码" src="/Verify/NumberVerifyCode?random=1994"
alt="vcode" style="cursor:pointer;" onclick="refreshNum()" />
<a href="javascript:void(0);" onclick="refreshNum()">看不清,换一张</a>
<h2>图形字母验证码</h2>
<img id="abcImgJson" title="图形字母验证码Json获取"
alt="vcode" style="cursor:pointer;" onclick="refreshAbcJson()" />
<a href="javascript:void(0);" onclick="refreshAbcJson()">看不清,换一张</a>
<img id="abcImg" title="图形字母验证码" src="/Verify/AbcVerifyCode?random=1994"
alt="vcode" style="cursor:pointer;" onclick="refreshAbc()" />
<a href="javascript:void(0);" onclick="refreshAbc()">看不清,换一张</a>
<h2>图形混合验证码</h2>
<img id="mixImgJson" title="图形混合验证码Json获取"
alt="vcode" style="cursor:pointer;" onclick="refreshMixJson()" />
<a href="javascript:void(0);" onclick="refreshMixJson()">看不清,换一张</a>
<img id="mixImg" title="图形混合验证码" src="/Verify/MixVerifyCode?random=1994"
alt="vcode" style="cursor:pointer;" onclick="refreshMix()" />
<a href="javascript:void(0);" onclick="refreshMix()">看不清,换一张</a>

5.效果如图

开源地址 动动小手,点个推荐吧!

注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目

务必收藏备用:.net core中通过Json或直接获取图形验证码(数字验证码、字母验证码、混合验证码),有源代码全实战demo(开源代码.net core3.0)的更多相关文章

  1. 如何在ASP.NET Core中使用JSON Patch

    原文: JSON Patch With ASP.NET Core 作者:.NET Core Tutorials 译文:如何在ASP.NET Core中使用JSON Patch 地址:https://w ...

  2. ASP.NET Core中返回 json 数据首字母大小写问题

    ASP.NET Core中返回 json 数据首字母大小写问题 在asp.net core中使用ajax请求动态绑定数据时遇到该问题 后台返回数据字段首字母为定义的大写,返回的数据没有问题 但是在前台 ...

  3. [08]ASP.NET Core 中 launchsettings.json 启动配置文件

    ASP.NET Core launchsettings.json 启动配置文件 本文作者:梁桐铭- 微软最有价值专家(Microsoft MVP) 文章会随着版本进行更新,关注我获取最新版本 本文出自 ...

  4. 【NET Core】.NET Core中读取json配置文件

    在.NET Framework框架下应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别用 Sy ...

  5. ASP.Net Core中设置JSON中DateTime类型的格式化(解决时间返回T格式)

    最近项目有个新同事,每个API接口里返回的时间格式中都带T如:[2019-06-06T10:59:51.1860128+08:00],其实这个主要是ASP.Net Core自带时间格式列化时间格式设置 ...

  6. Asp.Net Core中Json序列化处理整理

    一.Asp.Net Core中的Json序列化处理使用的是Newtonsoft.Json,更多参考:C# Newtonsoft.Json JsonSerializerSettings配置序列化操作,C ...

  7. [翻译]在 .NET Core 中的并发编程

    原文地址:http://www.dotnetcurry.com/dotnet/1360/concurrent-programming-dotnet-core 今天我们购买的每台电脑都有一个多核心的 C ...

  8. JavaScript中,JSON格式的字符串与JSON格式的对象相互转化

    前言:JSON是一个独立于任何语言的数据格式,因此,严格来说,没有“JSON对象”和“JSON字符串”这个说法(然而”菜鸟教程“和”W3school“使用了“JSON对象”和“JSON字符串”这个说法 ...

  9. .NET Core 中的并发编程

    今天我们购买的每台电脑都有一个多核心的 CPU,允许它并行执行多个指令.操作系统通过将进程调度到不同的内核来发挥这个结构的优点. 然而,还可以通过异步 I/O 操作和并行处理来帮助我们提高单个应用程序 ...

随机推荐

  1. MongoDB4.0支持事务管理

    ​ 背景 最后我们看一下MongoDB的事务管理,本来是没这一篇的,因为网上大部分资料太老,都为MongoDB之前的版本,的确在MongoDB 4.0版本之前是没有事务管理,但是今天年初MongoDB ...

  2. Shell之StdI/O和Pipe

    目录 Shell之StdI/O和Pipe 参考 StdI/O重定向 Pipe 常用组合 Shell之StdI/O和Pipe

  3. Shell之Xargs命令

    目录 Shell之Xargs命令 参考 xargs命令简介 xargs命令格式 xargs实例说明 Shell之Xargs命令

  4. Windows10+YOLOv3实现检测自己的数据集(1)——制作自己的数据集

    本文将从以下三个方面介绍如何制作自己的数据集 数据标注 数据扩增 将数据转化为COCO的json格式 参考资料 一.数据标注 在深度学习的目标检测任务中,首先要使用训练集进行模型训练.训练的数据集好坏 ...

  5. k8s pod访问不通外网问题排查

    环境概况 自建k8s集群,主机操作系统ubuntu16.04,k8s版本v1.14, 集群网络方案calico-3.3.6. worker节点数50+,均为GPU物理服务器,服务器类型异构,如Nvid ...

  6. 你也可以写聊天程序 - C# Socket学习1

    简述 我们做软件工作的虽然每天都离不开网络,可网络协议细节却不是每个人都会接触和深入了解.我今天就来和大家一起学习下Socket,并写一个简单的聊天程序. 一些基础类 首先我们每天打开浏览器访问网页信 ...

  7. 强大得分布式项目管理工具Git

    ---恢复内容开始--- 强大的分布式管理工具-Git(一) 前言:最近忙着写项目,在期间呢,用的是git管理,由于一个项目的管理是很重要得,所以整理了一篇关于git得博客跟大家分享一下.大家都知道, ...

  8. JZOJ10004 列车调度

    [JZOJ100041]列车调度 Description Input Output Sample Input Sample1: 3 1 2 3 Sample2: 9 1 3 2 4 8 6 9 5 7 ...

  9. Windows 服务程序(一)

    Windows 服务程序简介: Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合. 它没有用户界面,并且也不会产生任何可视输出.任何用户消息都会被写进Windows事件 ...

  10. 爬虫4:pdf页面+pdfminer模块+demo

    本文介绍下pdf页面的爬取,需要借助pdfminer模块 demo一般流程: 1)设置url url = 'http://www.------' + '.PDF' 2)requests模块获取url ...