Asp.net web api implements the image click verification code,

Source: Internet
Author: User

Asp.net web api implements the image click verification code,

Today, more and more verification codes are available. Today, you need to click the text in the image to verify the verification code,

This verification code verifies whether the mouse selects the text position in the image and the sequence of selection. When the verification code is generated, a set of basemap can be provided, a random image is obtained, and several words are randomly selected, then, the text order is disrupted and randomly placed on the image. Then, the text position and order are recorded. Verify the text position and order.

Verification Code image class

/// <Summary> /// QR code picture /// </summary> public class VerCodePic {/// <summary> /// picture link /// </summary> public string PicURL {get; set ;}//< summary> /// the first word location /// </summary> public FontPoint Font1 {get; set ;} /// <summary> /// location of the second word /// </summary> public FontPoint Font2 {get; set ;} /// <summary> /// the third character location /// </summary> public FontPoint Font3 {get; set ;} /// <summary> /// location of the fourth character /// </summary> public FontPoint Font4 {get; set ;}} /// <summary> /// Text Location /// </summary> public class FontPoint {public int X {get; set;} public int Y {get; set ;}}

In this method, the font size of the generated Verification Code image is 20 pixels, because the size of the Verification Code basemap is fixed, therefore, the verification code base map is divided into several grid locations based on the font size. to specify the position of a text in the image, you only need to randomly obtain a grid, if no text is specified in the grid, put the text in the grid.

How to Set grid in advance

  private static ArrayList _FontPoint;        public static ArrayList FontPoint        {            get            {                if (_FontPoint==null)                {                    _FontPoint = new ArrayList();                    for (int x=0;x<10;x++)                    {                        for (int y=0;y<5;y++)                        {                            _FontPoint.Add(new Models.FontPoint() { X = x * 28, Y = y * 20 });                        }                    }                }                return _FontPoint;            }        }

The verification code basemap I selected is 280*100. Therefore, the image is divided into several grids according to the above method. When setting a text position below, a random position is selected, in addition, different colors are set for each word.

/// <Summary> /// obtain the verification code Image Based on the text and image /// </summary> /// <param name = "content"> </param> // /<param name = "picFileName"> </param> // <returns> </returns> public static VerCodePic GetVerCodePic (string content, string picFileName, int fontSize = 20) {ClassLoger. info ("FileHelper. getVerCodePic "," start generating QR code "); Bitmap bmp = new Bitmap (picFileName); List <int> hlist = new List <int> (); VerCodePic codepic = new VerCodePic (); Int I = Utils. getRandom (0, SystemSet. fontPoint. count-1); codepic. font1 = SystemSet. fontPoint [I] as FontPoint; hlist. add (I); A: int i2 = Utils. getRandom (0, SystemSet. fontPoint. count-1); if (hlist. contains (i2) goto A; codepic. font2 = SystemSet. fontPoint [i2] as FontPoint; hlist. add (i2); B: int i3 = Utils. getRandom (0, SystemSet. fontPoint. count-1); if (hlist. contains (i3) goto B; hlist. add (I 3); codepic. font3 = SystemSet. fontPoint [i3] as FontPoint; C: int i4 = Utils. getRandom (0, SystemSet. fontPoint. count-1); if (hlist. contains (i4) goto C; hlist. add (i4); codepic. font4 = SystemSet. fontPoint [i4] as FontPoint; string fileName = (content + "-" + picFileName + "-" + I + "|" + i2 + "|" + i3 + "|" + i4 ). MD5 () + Path. getExtension (picFileName); string dir = Path. combine (SystemSet. resourcesPath, SystemSet. verCo DePicPath); string filePath = Path. combine (dir, fileName); if (File. exists (filePath) {codepic. picURL = string. format ("{0}/{1}/{2}", SystemSet. webResourcesSite, SystemSet. verCodePicPath, fileName); return codepic;} if (! Directory. exists (dir) {Directory. createDirectory (dir);} Graphics g = Graphics. fromImage (bmp); Font font = new Font ("", fontSize, GraphicsUnit. pixel); SolidBrush sbrush = new SolidBrush (Color. black); SolidBrush sbrush1 = new SolidBrush (Color. peru); SolidBrush sbrush2 = new SolidBrush (Color. yellowGreen); SolidBrush sbrush3 = new SolidBrush (Color. skyBlue); List <char> fontlist = content. toList (); ClassLoger. info ("FileHelper. getVerCodePic ", fontlist. count. toString (); g. drawString (fontlist [0]. tryToString (), font, sbrush, new PointF (codepic. font1.X, codepic. font1.Y); g. drawString (fontlist [1]. tryToString (), font, sbrush1, new PointF (codepic. font2.X, codepic. font2.Y); g. drawString (fontlist [2]. tryToString (), font, sbrush2, new PointF (codepic. font3.X, codepic. font3.Y); g. drawString (fontlist [3]. tryToString (), font, sbrush3, new PointF (codepic. font4.X, codepic. font4.Y); bmp. save (filePath, ImageFormat. jpeg); codepic. picURL = string. format ("{0}/{1}/{2}", SystemSet. webResourcesSite, SystemSet. verCodePicPath, fileName); return codepic ;}

The api used to obtain the image Verification Code. In this api, an idiom is randomly selected from the idiom library, an image is randomly selected, and the method for generating the image verification code is called, the image verification code is generated, and the information corresponding to the Verification code is cached in redis. The cache time is set and the redis key is returned as a temporary token along with the verification code.

/// <Summary> /// obtain the verification code, validity Period: 10 minutes /// </summary> /// <returns> </returns> [HttpGet] [Route ("vercode")] public JsonResult <VerCodePicViewModel> VerCodePic () {JsonResult <VerCodePicViewModel> result = new JsonResult <VerCodePicViewModel> (); result. code = 1; result. msg = "OK"; try {ClassLoger. info ("VerCodePic", "getting idioms"); cy_dictBll cybll = new cy_dictBll (); IList <cy_dict> cylist = cybll. getAllcy_dict (); ClassLoger. info ("VerCodePic", cylist. count. toString (); int I = Utils. getRandom (0, cylist. count-1); ClassLoger. info ("VerCodePic", I. toString (); cy_dict cy = cylist [I]; ClassLoger. info ("VerCodePic idiom:", cy. chengyu); VerCodePicViewModel vcvm = new VerCodePicViewModel (); string sourcePic = FileHelper. getVerCodePicResource (); if (sourcePic. isNull () |! File. exists (sourcePic) {sourcePic = @ "E: \ WebResources \ images \ VerCodePicSource \ 1.jpg";} ClassLoger. info ("VerCodePic image", sourcePic); VerCodePic codepic = FileHelper. getVerCodePic (cy. chengyu, sourcePic); vcvm. content = cy. chengyu; vcvm. mainPic = codepic. picURL; result. result = vcvm; string key = cookieKey (); RedisBase. item_Set (key, codepic); RedisBase. expireEntryAt (key, DateTime. now. addMinutes (10); result. resultMsg = key;} catch (Exception ex) {ClassLoger. error ("AccountController. verCodePic ", ex); result. code =-1; result. msg = "AccountController. verCodePic exception: "+ ex. message;} return result ;}

Effect

Parameter structure of image verification code verification Interface

Public class CheckPicCodeViewModel {// <summary> // client token // </summary> public string token {get; set;} public double x1 {get; set ;} public double x2 {get; set;} public double x3 {get; set;} public double x4 {get; set;} public double y1 {get; set ;} public double y2 {get; set;} public double y3 {get; set;} public double y4 {get; set ;}}

Verification code verification Interface

/// <Summary> /// check whether the image verification code is correct /// </summary> /// <param name = "piccode"> </param> // <returns> </returns> [HttpPost] [Route ("checkpiccode")] public async Task <IHttpActionResult> CheckPicCode ([FromBody] CheckPicCodeViewModel piccode) {JsonResult <bool> result = new JsonResult <bool> (); result. code = 1; result. msg = "OK"; if (piccode = null) {result. result = false; result. resultMsg = "parameter error"; return OK (Result);} if (string. IsNullOrEmpty (piccode. token) |! RedisBase. containsKey (piccode. token) {result. result = false; result. resultMsg = "Verification Code expired"; return OK (result);} result. result = await Task. run <bool> () => {bool flag = false; VerCodePic codepic = RedisBase. item_Get <VerCodePic> (piccode. token); if (Math. abs (codepic. font1.X-piccode. x1)> 0.5 | Math. abs (codepic. font1.Y-piccode. y1)> 0.5 | Math. abs (codepic. font2.X-piccode. x2)> 0.5 | Math. abs (codepic. font2.Y-piccode. y2)> 0.5 | Math. abs (codepic. font3.X-piccode. x3)> 0.5 | Math. abs (codepic. font3.Y-piccode. y3)> 0.5 | Math. abs (codepic. font4.X-piccode. (x4)> 0.5 | Math. abs (codepic. font4.Y-piccode. y4)> 0.5) {flag = false; result. resultMsg = "Verification code error";} else {flag = true; result. resultMsg = "correct verification code";} return flag;}); return OK (result );}

Input the location and sequence selected by the user and verify it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.