Home > Article > Backend Development > asp.net click verification code implementation ideas
Haha, it’s been a long time since I posted it. Finally, I saw that clicking on the verification code was interesting, so I wanted to write one myself.
First the renderings
If you are attracted by this effect, please continue reading.
Let me give you some ideas before posting the code:
1. There must be a Chinese character library and classify it according to glyphs. (I classified the radicals in the database)
2. Get the verification code (that is, take a few characters to make the verification code)
3. Take it out based on Find the words with similar shapes
4. Arrange the verification code text and the words with similar shapes
5. Draw the picture
6. Display
1. Obtain the character library
Our country’s culture is profound and profound, where do so many spicy characters come from? Of course, I couldn't add it manually, so I randomly found a website that could look up Chinese characters on the Internet to capture other people's data. To capture data, please click on the portal. What is mentioned in the portal is just ideas. If you don’t understand anything, please tell me. I'll share my font library below.
2. Obtain the verification code
This is relatively simple. I will paste the code directly here. The following code is to randomly sort and take 4 pieces of data. I am like this Written for convenience. Personally, I think randomly generating the ID first, and then fetching the data directly based on the ID will make the query faster than the following writing method. (Note that the database I use is MySql)
/// <summary> /// 获取验证码 /// </summary> public List<VerificationCode.Model.WenZhi> GetCodeText() { const string sql = "SELECT * FROM wenzhi ORDER BY RAND() LIMIT 4"; var dataReader = dbHelper.GetDataReader(sql); var list = DataReaderToList(dataReader); dataReader.Close(); return list; }
3. Find similar words based on the extracted text
Because I saved the radical in the first step, so Here I directly obtain the close word of the current radical based on the radical.
/// <summary> /// 获取答案备选 /// </summary> /// <param name="buShouCode">部首编码</param> /// <param name="id">当前文字ID</param> /// <param name="number">数量</param> /// <returns></returns> public List<VerificationCode.Model.WenZhi> GetAnswer(string buShouCode, int id,int number=1) { string sql = $"SELECT * FROM wenzhi where BuShouCode='{buShouCode}' and ID <> {id} ORDER BY RAND() LIMIT "+ number; var dataReader = dbHelper.GetDataReader(sql); var list = DataReaderToList(dataReader); dataReader.Close(); return list; }
4. Arrange the verification code text and similar words
The following code first puts the alternative answers and verification codes in a set and then sorts the set
public Model.Code GetCode() { var wenzlist = _wenZhiDal.GetCodeText(); //获取验证码 var listAnsuwr = new List<Answer>();//实例化备选答案对象 var answerCode = string.Empty;//答案 var result = new Model.Code { Id = Guid.NewGuid().ToString() }; //根据验证码获取备选答案并把添加到答案添加到备选答案集合 foreach (var item in wenzlist) { answerCode += item.ID + ","; result.AnswerValue += item.Text; var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID); listAnsuwr.Add(new Answer { Id = item.ID.ToString(), Img = GetImage(item.Text) }); listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) })); } //如果答案个数不够就再去取几个 if (listAnsuwr.Count < 9) { var ran = new Random(); var randKey = ran.Next(0, 4); var item = wenzlist[randKey]; var answerList = _wenZhiDal.GetAnswer(item.BuShouCode, item.ID, 9 - listAnsuwr.Count); listAnsuwr.AddRange(answerList.Select(answer => new Answer { Id = answer.ID.ToString(), Img = GetImage(answer.Text) })); } result.CodeImg = GetImage(result.AnswerValue);//获取图片 result.AnswerValue = answerCode.TrimEnd(','); result.Answer = RandomSortList(listAnsuwr);//打乱正确答案与形近字的顺序 return result; }
This is the code for sorting the collection
/// <summary> /// 随机排列集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="listT"></param> /// <returns></returns> private static List<T> RandomSortList<T>(IEnumerable<T> listT) { var random = new Random(); var newList = new List<T>(); foreach (var item in listT) { newList.Insert(random.Next(newList.Count + 1), item); } return newList; }
5. Drawing pictures
The following is the code for drawing pictures. The verification code and alternative answers correspond to two different drawing methods. (The comments inside are fairly clear). Don’t worry that humans can’t tell the difference after the text is rotated x°, haha. In the last sentence of the code, I converted the image to Base64 to facilitate front-end calling.
private static string GetImage(string text) { Image image; switch (text.Length) { case 1: image = new Bitmap(50, 40); break; case 4: image = new Bitmap(120, 40); break; default: image = new Bitmap(50, 40); break; } Brush brushText = new SolidBrush(Color.FromArgb(255, 0, 0, 0)); var graphics = Graphics.FromImage(image); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.Clear(Color.White); var font = new Font(new FontFamily("华文彩云"), 20, FontStyle.Regular); if (text.Length > 1)//画验证码 { //先来两条直线做干扰 然后再画文字 graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(0, 10), new Random().Next(10, 40)), new Point(new Random().Next(100, 120), new Random().Next(10, 30))); graphics.DrawLine(new Pen(brushText, new Random().Next(1, 3)), new Point(new Random().Next(20, 50), new Random().Next(0, 10)), new Point(new Random().Next(100, 120), new Random().Next(30, 40))); graphics.DrawString(text, font, brushText, 0, 10); } else//画备选答案 { Point middle = new Point(25, 20); graphics.TranslateTransform(middle.X, middle.Y); //这里是360°随机旋转 graphics.RotateTransform(new Random().Next(0, 360)); var format = new StringFormat(StringFormatFlags.NoClip) { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; graphics.DrawString(text, font, brushText, 0, 0, format); } brushText.Dispose(); graphics.Dispose(); return ImageToBase64(image); }
6. Display
Directly calling the GetCode method can return the verification code object
The following is the background code, it should be that the correct answer is placed in AnswerValue, so I first take it out and put it in Session, then clear the value and then return it to the browser through json.
public string GetVerCode() { var code = new VerificationCode.Code().GetCode(); Session["VERCODE"] = code.AnswerValue; code.AnswerValue = ""; return JsonConvert.SerializeObject(code); }
Now let’s pile up some html code
<div class="form-group"> <ul class="vercode"> <li><img src=''/ alt="asp.net click verification code implementation ideas" ></li> <li><img src=''/ alt="asp.net click verification code implementation ideas" ></li> <li><img src=''/ alt="asp.net click verification code implementation ideas" ></li> <li><img src=''/ alt="asp.net click verification code implementation ideas" ></li> <li class="delete" onclick="delete_input()"></li> </ul> <div> <img id="code-image"/ alt="asp.net click verification code implementation ideas" > <a href="javascript:void(0);" onclick="load_vercode()">看不清?</a> </div> <ul class="vercode-anwser"> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> <li><img / alt="asp.net click verification code implementation ideas" ></li> </ul> </div>
Let’s add some js code. Here we only realize the effect on the picture, and we haven’t verified the data yet (here is the verification idea: each picture corresponds to An ID, get the ID of the selected picture separated by commas, and then compare it with the value in Session)
<script> $(function () { //加载验证码 load_vercode(); //绑定验证码点击事件 $(".vercode-anwser").find("img").on("click", null, function () { $(".vercode").find("img[src='']:eq(0)").attr("src", $(this).attr("src")); }); }); function load_vercode() { $(".vercode").find("img").attr("src", ""); $.get("GetVerCode", function (data) { var result = JSON.parse(data); $("#code-image").attr("src", "data:image/png;base64," + result.CodeImg); $(".vercode-anwser").find("img").each(function (index) { $(this).attr("src", "data:image/png;base64," + result.Answer[index].Img); }); }); } //删除事件 function delete_input() { $(".vercode").find("img[src!='']:last").attr("src", ""); } </script>
The code is almost here. The above ideas are just personal thoughts. Friends who are interested can discuss it together. Bar.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles related to asp.net click verification code implementation ideas, please pay attention to the PHP Chinese website!