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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.
