.NET Core 2.0如何生成图片验证码完整实例
程序员文章站
2022-03-09 21:44:51
前言
图片验证码在我们日常开发中是必不可少会遇见的一个功能,最近工作中就遇到了这个需求,所以下面将实现的方法分享给大家,话不多说了,来一起看看详细的介绍吧。
.net...
前言
图片验证码在我们日常开发中是必不可少会遇见的一个功能,最近工作中就遇到了这个需求,所以下面将实现的方法分享给大家,话不多说了,来一起看看详细的介绍吧。
.net core 2.0生成图片验证码
nuget包引入:zkweb.system.drawing,如下所示:
代码实例如下:verifycodehelper
using system; using system.drawingcore; using system.drawingcore.drawing2d; using system.drawingcore.imaging; using system.io; namespace common.helper { public sealed 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(0, int32.maxvalue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginseek += 10000; seeks[i] = beginseek; } //生成随机数字 for (int i = 0; i < length; i++) { random rand = new random(seeks[i]); int pownum = 1 * (int)math.pow(10, length); randmembers[i] = rand.next(pownum, int32.maxvalue); } //抽取随机数字 for (int i = 0; i < length; i++) { string numstr = randmembers[i].tostring(); int numlength = numstr.length; random rand = new random(); int numposition = rand.next(0, numlength - 1); validatenums[i] = int32.parse(numstr.substring(numposition, 1)); } //生成验证码 for (int i = 0; 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 = 0; i < length; i++) { verification[i] = dictionary[random.next(dictionary.length - 1)]; } 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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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 = 0; i < length; i++) { verification[i] = dictionary[random.next(dictionary.length - 1)]; } 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(4, 6); 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", 14, (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(0, (height - totalsizef.height) / 2); random random = new random(); //随机数产生器 g.clear(color.white); //清空图片背景色 for (int i = 0; i < verifycode.length; i++) { brush = new lineargradientbrush(new point(0, 0), new point(1, 1), color.fromargb(random.next(255), random.next(255), random.next(255)), color.fromargb(random.next(255), random.next(255), random.next(255))); g.drawstring(verifycode[i].tostring(), font, brush, startpointf); curcharsizef = g.measurestring(verifycode[i].tostring(), font); startpointf.x += curcharsizef.width; } //画图片的干扰线 for (int i = 0; i < 10; 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 = 0; i < 100; 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), 0, 0, bitmap.width - 1, bitmap.height - 1); //画图片的边框线 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", 14, (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(0, (height - totalsizef.height) / 2); random random = new random(); //随机数产生器 g.clear(color.white); //清空图片背景色 for (int i = 0; i < verifycode.length; i++) { brush = new lineargradientbrush(new point(0, 0), new point(1, 1), color.fromargb(random.next(255), random.next(255), random.next(255)), color.fromargb(random.next(255), random.next(255), random.next(255))); g.drawstring(verifycode[i].tostring(), font, brush, startpointf); curcharsizef = g.measurestring(verifycode[i].tostring(), font); startpointf.x += curcharsizef.width; } //画图片的干扰线 for (int i = 0; i < 10; 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 = 0; i < 100; 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), 0, 0, bitmap.width - 1, bitmap.height - 1); //画图片的边框线 g.dispose(); //保存图片数据 memorystream stream = new memorystream(); bitmap.save(stream, imageformat.jpeg); //输出图片流 return stream.toarray(); } #endregion } }
新建控制器:verifycodecontroller,
using system.drawingcore.imaging; using system.io; using common.helper; using microsoft.aspnetcore.mvc; namespace webapplicationapi.controllers { public class verifycodecontroller : controller { public iactionresult index() { return view(); } /// <summary> /// 数字验证码 /// </summary> /// <returns></returns> public filecontentresult numberverifycode() { string code = verifycodehelper.getsingleobj().createverifycode(verifycodehelper.verifycodetype.numberverifycode); byte[] codeimage = verifycodehelper.getsingleobj().createbytebyimgverifycode(code, 100, 40); return file(codeimage, @"image/jpeg"); } /// <summary> /// 字母验证码 /// </summary> /// <returns></returns> public filecontentresult abcverifycode() { string code = verifycodehelper.getsingleobj().createverifycode(verifycodehelper.verifycodetype.abcverifycode); var bitmap = verifycodehelper.getsingleobj().createbitmapbyimgverifycode(code, 100, 40); memorystream stream = new memorystream(); bitmap.save(stream, imageformat.png); return file(stream.toarray(), "image/png"); } /// <summary> /// 混合验证码 /// </summary> /// <returns></returns> public filecontentresult mixverifycode() { string code = verifycodehelper.getsingleobj().createverifycode(verifycodehelper.verifycodetype.mixverifycode); var bitmap = verifycodehelper.getsingleobj().createbitmapbyimgverifycode(code, 100, 40); memorystream stream = new memorystream(); bitmap.save(stream, imageformat.gif); return file(stream.toarray(), "image/gif"); } } }
添加页面index.cshtml,如下代码:
@{ layout = null; } <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>index</title> </head> <body> <figure> <h3>图片验证码</h3> <fieldset> <legend>数字验证码</legend> <img id="nubimg" title="数字验证码" src="/verifycode/numberverifycode?random=" alt="vcode" onclick="refresh()" style="cursor:pointer;" /> </fieldset> <fieldset> <legend>数字验证码</legend> <img id="abcimg" title="字母验证码" src="/verifycode/abcverifycode" alt="vcode" onclick="this.src=this.src+'?'" style="cursor:pointer;" /> </fieldset> <fieldset> <legend>混合验证码</legend> <img id="miximg" title="数字字母混合验证码" src="/verifycode/mixverifycode" alt="vcode" onclick="this.src=this.src+'?'" style="cursor:pointer;" /> </fieldset> </figure> <script type="text/javascript"> function refresh() { var id = document.getelementbyid("nubimg"); var str = "/verifycode/numberverifycode?random=" + math.random(); id.setattribute("src", str); } </script> </body> </html>
生成验证码如下所示:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。