很多人写的博客大家看了会一知半解,不知道怎么用,应该引用什么类库或者代码不全,这样很多小白很是头疼,尤其是尝新技术更是如此。我们这边不止告诉你步骤,而且还提供开源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. 玩转 SpringBoot 2 之整合 JWT 上篇

    前言 该文主要带你了解什么是 JWT,以及JWT 定义和先关概念的介绍,并通过简单Demo 带你了解如何使用 SpringBoot 2 整合 JWT. 介绍前在这里我们来探讨一下如何学习一门新的技术, ...

  2. Thinkphp5.0第一篇

    THINKphp5.0框架 mvc moudle(数据)+view(表现层)+controller(业务逻辑) thinkphp5.0特点 中国人开发最符合国人习惯和思维方式 开源免费面向对象轻量级的 ...

  3. maven打包工程出现错误 Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test

    今天用maven在命令行打包项目的时候出现错误: Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12. ...

  4. PHP7源码之array_flip函数分析

    以下源码基于 PHP 7.3.8 array array_flip ( array $array ) (PHP 4, PHP 5, PHP 7) array_flip - 交换数组中的键和值 arra ...

  5. ThoughtWorks 面试三连挂,以后再也不去了

    先说我吧,之前在外企呆过两年,那时Team的很多同事都去了ThoughtWorks,所以有一种情怀,只要有机会我就去面试...之前在Team里对我的评价也很高(不是我说的),现在也是公司的技术总监,总 ...

  6. appium-doctor报错“JAVA_HOME is set but does not exist on the file system at "D:\work\eclipse\Java\jdk1.7.0_67;"”解决办法

    卸载了jdk重新安装,重新配置环境就可以了

  7. C#刷遍Leetcode面试题系列连载(4) No.633 - 平方数之和

    上篇文章中一道数学问题 - 自除数,今天我们接着分析 LeetCode 中的另一道数学题吧~ 今天要给大家分析的面试题是 LeetCode 上第 633 号问题, Leetcode 633 - 平方数 ...

  8. Head First设计模式——观察者模式

    1.气象监测应用,错误示范 有一个气象站,分别有三个装置:温度感应装置,湿度感应装置,气压感应装置.WeathData对象跟踪气象站数据,WeathData有MeasurmentsChanged()方 ...

  9. python-Flask模版注入攻击SSTI(python沙盒逃逸)

    一篇以python Flask 模版渲染为例子的SSTI注入教学~ 0x01 Flask使用和渲染 这里简化了flask使用和渲染的教程 只把在安全中我们需要关注的部分写出来 来一段最简单的FLASK ...

  10. php中代码执行&&命令执行函数

    转自i春秋 1.eval()函数 #传入的参数必须为PHP代码,既需要以分号结尾. #命令執行:cmd=system(whoami); #菜刀连接密码:cmd <?php @eval($_POS ...