【无私分享:ASP.NET CORE 项目实战(第十四章)】图形验证码的实现

 

目录索引 

 

【无私分享:ASP.NET CORE 项目实战】目录索引html

 

简介

 

  

  很长时间没有来更新博客了,一是,最近有些忙,二是,Core也是一直在摸索中,其实已经完成了一个框架了,而且正在准备在生产环境中试用,可是不少东西也是出于本身理解的肤浅和技术的不断更新,常常变更,因此,若是本身尚未彻底搞好,就来写博客,反复的修正,可能会误导一些新手朋友。linux

  若是有正在研究Core的朋友,能够你们一块儿交流下。git

 

 

验证码  

  

  相信不少朋友跟我同样,图形验证码成为了 Core 的一个绊脚石。github

 

  System.Drawing.Primitives 这是官方的一个Drawing库,可是没有Bitmap、Graphics等不少东西,因此这个作图形验证码基本Pass了。web

 

     CoreCompat.System.Drawing 这个是一个第三方的,使用了mono的System.Drawing实现,只要安装了以前使用System.Drawing的代码彻底不用修改,也支持描画验证码等描画类的功能。若是须要linux或osx支持,能够安装runtime.linux.CoreCompat.System.Drawing和runtime.osx.10.10-x64.CoreCompat.System.Drawing。(地址:https://github.com/CoreCompat/CoreCompat),基本你们都是在用这个吧,这个在Windows下是没有任何问题的,在Linux上一直没有成功,也不知道是本身编译的问题仍是什么问题。算法

 

 

   zkweb.system.drawing 这个也是第三方的,从mono的System.Drawing修改得来的。过程比较详细,也实现了。因此把这个的使用跟你们分享一下。windows

 

  这个类库和CoreCompat的不一样点以下数组

 

    • 没有使用强名称,CoreCompat为了让程序集名称同样使用了一个伪造的签名,可是致使Asp.Net和Owin等会检查签名的旧项目启动失败
    • CoreCompat的项目若是直接下载编译会出现100多个错误,大可能是类型找不到的错误,我也不知道做者是怎么编译过去的
      这个项目从mono 4.6.1.13复制了全部须要的文件并修改,直接下载编译就能够经过
    • 可使用dotnet test跑单元测试,目前经过率约为80%
    • 实际在linux上测试过而且给出了各个发行版安装libgdiplus的命令,目前已测试不引用System.Drawing.Primitive,由于System.Drawing.Primitive在.Net Framework下同时引用了原来的System.Drawing,有可能致使编译时类型冲突(实测只有警告)
      • Ubuntu Server 16.04 LTS 64bit
      • Fedora 24 64bit
      • CentOS 7.2 64bit

 

 

 

Zkweb.system.drawing

  首先经过Nuget: Install-Package ZKWeb.System.Drawing 添加 引用服务器

   

 

简单的图形验证码生成:

 

  

 1  public class VierificationCodeServices
 2     {
 3         /// <summary>  
 4         /// 该方法用于生成指定位数的随机数  
 5         /// </summary>  
 6         /// <param name="VcodeNum">参数是随机数的位数</param>  
 7         /// <returns>返回一个随机数字符串</returns>  
 8         private string RndNum(int VcodeNum)
 9         {
10             //验证码能够显示的字符集合  
11             string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" +
12                 ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" +
13                 ",R,S,T,U,V,W,X,Y,Z";
14             string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分红数组   
15             string code = "";//产生的随机数  
16             int temp = -1;//记录上次随机数值,尽可能避避免生产几个同样的随机数  
17 
18             Random rand = new Random();
19             //采用一个简单的算法以保证生成随机数的不一样  
20             for (int i = 1; i < VcodeNum + 1; i++)
21             {
22                 if (temp != -1)
23                 {
24                     rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类  
25                 }
26                 int t = rand.Next(61);//获取随机数  
27                 if (temp != -1 && temp == t)
28                 {
29                     return RndNum(VcodeNum);//若是获取的随机数重复,则递归调用  
30                 }
31                 temp = t;//把本次产生的随机数记录起来  
32                 code += VcArray[t];//随机数的位数加一  
33             }
34             return code;
35         }
36 
37         /// <summary>  
38         /// 该方法是将生成的随机数写入图像文件  
39         /// </summary>  
40         /// <param name="code">code是一个随机数</param>
41         /// <param name="numbers">生成位数(默认4位)</param>  
42         public MemoryStream Create(out string code, int numbers = 4)
43         {
44             code = RndNum(numbers);
45             Bitmap Img = null;
46             Graphics g = null;
47             MemoryStream ms = null;
48             Random random = new Random();
49             //验证码颜色集合  
50             Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
51 
52             //验证码字体集合
53             string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
54 
55 
56             //定义图像的大小,生成图像的实例  
57             Img = new Bitmap((int)code.Length * 18, 32);
58 
59             g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象    
60 
61             g.Clear(Color.White);//背景设为白色  
62 
63             //在随机位置画背景点  
64             for (int i = 0; i < 100; i++)
65             {
66                 int x = random.Next(Img.Width);
67                 int y = random.Next(Img.Height);
68                 g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
69             }
70             //验证码绘制在g中  
71             for (int i = 0; i < code.Length; i++)
72             {
73                 int cindex = random.Next(7);//随机颜色索引值  
74                 int findex = random.Next(5);//随机字体索引值  
75                 Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体  
76                 Brush b = new SolidBrush(c[cindex]);//颜色  
77                 int ii = 4;
78                 if ((i + 1) % 2 == 0)//控制验证码不在同一高度  
79                 {
80                     ii = 2;
81                 }
82                 g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符  
83             }
84             ms = new MemoryStream();//生成内存流对象  
85             Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中  
86 
87             //回收资源  
88             g.Dispose();
89             Img.Dispose();
90             return ms;
91         }
92     }

 

 

 

测试运行

 

  在Controller中新建一个 IActionResult 用于输出验证码:框架

  

 1      /// <summary>
 2         /// 图形验证码
 3         /// </summary>
 4         /// <returns></returns>
 5         public IActionResult ValidateCode([FromServices]VierificationCodeServices _vierificationCodeServices)
 6         {
 7             string code = "";
 8             System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code);
 9             HttpContext.Session.SetString("LoginValidateCode", code);
10             Response.Body.Dispose();
11             return File(ms.ToArray(), @"image/png");
12         }

 

 

 

   前台输出:<img id="imgVerify" src="/sysmanage/account/ValidateCode" alt="看不清?点击更换" onclick="this.src = this.src + '?'" style="vertical-align:middle;" />

 Windows

 

  咱们在Windows下运行一下:

  

 

Linux(CentOS7)

 

    咱们按照步骤,执行如下命令:  

     yum install autoconf automake libtool


     yum install freetype-devel fontconfig libXft-devel


     yum install libjpeg-turbo-devel libpng-devel giflib-devel libtiff-devel libexif-devel


     yum install glib2-devel cairo-devel


     git clone https://github.com/mono/libgdiplus (若是没有安装git命令 执行yum install git 安装)

              wget http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/l/libgdiplus-2.10-9.el7.x86_64.rpm(若是没有安装wget命令 执行yum install wget)

    wget http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/l/libgdiplus-devel-2.10-9.el7.x86_64.rpm

    rpm -Uvh libgdiplus-2.10-9.el7.x86_64.rpm

    rpm -Uvh libgdiplus-devel-2.10-9.el7.x86_64.rpm

     cd libgdiplus


     ./autogen.sh


     make


     make install


     cd /usr/lib64/


     ln -s /usr/local/lib/libgdiplus.so gdiplus.dll

 

   把咱们发布好的项目上传到Linux服务器上,进入项目目录:

  cd OcelotWeb

  dotnet Ocelot.Web.dll

   

 

  咱们的打开网站看一下:

  

 

  没有显示出来,咱们看下运行的日志:

  

 

  FontFamily Not Found,字体的错误,咱们看一下咱们的代码:

  

 

  这些字体Linux没有,这个解决办法不少,这里我用了最简单的,我不想再去修改个人代码,我就直接把windows下的这些字体拷贝出来:

  

  上传到服务器的 /usr/share/fonts/chinese/TrueType 目录下(chinese/TrueType 两个目录是本身建立的)

  进入这个目录:

  cd /usr/share/fonts/chinese/TrueType

  mkfontscale(若是提示 mkfontscale: command not found,需自行安装 # yum install mkfontscale )

  mkfontdir

   fc-cache -fv(若是提示 fc-cache: command not found,则须要安装# yum install fontconfig )

  

  再次打开以前的页面:

  

 

   出现了!

 

 

 

 

 

 

 

但愿跟你们一块儿学习Asp.net Core 

刚开始接触,水平有限,不少东西都是本身的理解和翻阅网上大神的资料,若是有不对的地方和不理解的地方,但愿你们指正!

虽然Asp.net Core 如今很火热,可是网上的不少资料都是前篇一概的复制,因此有不少问题我也暂时没有解决,但愿你们能共同帮助一下!

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

相关文章
相关标签/搜索