


This article mainly introduces the complete code class of C#generating beautiful verification code. Has very good reference value. Let’s take a look with the editor below
Without further ado, please look at the code:
using System; using System.Web; using System.Drawing; using System.Security.Cryptography; namespace DotNet.Utilities { /// <summary> /// 验证码类 /// </summary> public class Rand { #region 生成随机数字 /// <summary> /// 生成随机数字 /// </summary> /// <param name="length">生成长度</param> public static string Number(int Length) { return Number(Length, false); } /// <summary> /// 生成随机数字 /// </summary> /// <param name="Length">生成长度</param> /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param> public static string Number(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); string result = ""; System.Random random = new Random(); for (int i = 0; i < Length; i++) { result += random.Next(10).ToString(); } return result; } #endregion #region 生成随机字母与数字 /// <summary> /// 生成随机字母与数字 /// </summary> /// <param name="IntStr">生成长度</param> public static string Str(int Length) { return Str(Length, false); } /// <summary> /// 生成随机字母与数字 /// </summary> /// <param name="Length">生成长度</param> /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param> public static string Str(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); char[] Pattern = new char[] { '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' }; string result = ""; int n = Pattern.Length; System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < Length; i++) { int rnd = random.Next(0, n); result += Pattern[rnd]; } return result; } #endregion #region 生成随机纯字母随机数 /// <summary> /// 生成随机纯字母随机数 /// </summary> /// <param name="IntStr">生成长度</param> public static string Str_char(int Length) { return Str_char(Length, false); } /// <summary> /// 生成随机纯字母随机数 /// </summary> /// <param name="Length">生成长度</param> /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param> public static string Str_char(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); char[] Pattern = new char[] { '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' }; string result = ""; int n = Pattern.Length; System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < Length; i++) { int rnd = random.Next(0, n); result += Pattern[rnd]; } return result; } #endregion } /// <summary> /// 验证图片类 /// </summary> public class YZMHelper { #region 私有字段 private string text; private Bitmap image; private int letterCount = 4; //验证码位数 private int letterWidth = 16; //单个字体的宽度范围 private int letterHeight = 20; //单个字体的高度范围 private static byte[] randb = new byte[4]; private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); private Font[] fonts = { new Font(new FontFamily("Times New Roman"),10 +Next(1),System.Drawing.FontStyle.Regular), new Font(new FontFamily("Georgia"), 10 + Next(1),System.Drawing.FontStyle.Regular), new Font(new FontFamily("Arial"), 10 + Next(1),System.Drawing.FontStyle.Regular), new Font(new FontFamily("Comic Sans MS"), 10 + Next(1),System.Drawing.FontStyle.Regular) }; #endregion #region 公有属性 /// <summary> /// 验证码 /// </summary> public string Text { get { return this.text; } } /// <summary> /// 验证码图片 /// </summary> public Bitmap Image { get { return this.image; } } #endregion #region 构造函数 public YZMHelper() { HttpContext.Current.Response.Expires = 0; HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1); HttpContext.Current.Response.AddHeader("pragma", "no-cache"); HttpContext.Current.Response.CacheControl = "no-cache"; this.text = Rand.Number(4); CreateImage(); } #endregion #region 私有方法 /// <summary> /// 获得下一个随机数 /// </summary> /// <param name="max">最大值</param> private static int Next(int max) { rand.GetBytes(randb); int value = BitConverter.ToInt32(randb, 0); value = value % (max + 1); if (value < 0) value = -value; return value; } /// <summary> /// 获得下一个随机数 /// </summary> /// <param name="min">最小值</param> /// <param name="max">最大值</param> private static int Next(int min, int max) { int value = Next(max - min) + min; return value; } #endregion #region 公共方法 /// <summary> /// 绘制验证码 /// </summary> public void CreateImage() { int int_ImageWidth = this.text.Length * letterWidth; Bitmap image = new Bitmap(int_ImageWidth, letterHeight); Graphics g = Graphics.FromImage(image); g.Clear(Color.White); for (int i = 0; i < 2; i++) { int x1 = Next(image.Width - 1); int x2 = Next(image.Width - 1); int y1 = Next(image.Height - 1); int y2 = Next(image.Height - 1); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } int _x = -12, _y = 0; for (int int_index = 0; int_index < this.text.Length; int_index++) { _x += Next(12, 16); _y = Next(-2, 2); string str_char = this.text.Substring(int_index, 1); str_char = Next(1) == 1 ? str_char.ToLower() : str_char.ToUpper(); Brush newBrush = new SolidBrush(GetRandomColor()); Point thePos = new Point(_x, _y); g.DrawString(str_char, fonts[Next(fonts.Length - 1)], newBrush, thePos); } for (int i = 0; i < 10; i++) { int x = Next(image.Width - 1); int y = Next(image.Height - 1); image.SetPixel(x, y, Color.FromArgb(Next(0, 255), Next(0, 255), Next(0, 255))); } image = TwistImage(image, true, Next(1, 3), Next(4, 6)); g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1)); this.image = image; } /// <summary> /// 字体随机颜色 /// </summary> public Color GetRandomColor() { Random RandomNum_First = new Random((int)DateTime.Now.Ticks); System.Threading.Thread.Sleep(RandomNum_First.Next(50)); Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks); int int_Red = RandomNum_First.Next(180); int int_Green = RandomNum_Sencond.Next(180); int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green; int_Blue = (int_Blue > 255) ? 255 : int_Blue; return Color.FromArgb(int_Red, int_Green, int_Blue); } /// <summary> /// 正弦曲线Wave扭曲图片 /// </summary> /// <param name="srcBmp">图片路径</param> /// <param name="bXDir">如果扭曲则选择为True</param> /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param> /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param> public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) { double PI = 6.283185307179586476925286766559; Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); Graphics graph = Graphics.FromImage(destBmp); graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height); graph.Dispose(); double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width; for (int i = 0; i < destBmp.Width; i++) { for (int j = 0; j < destBmp.Height; j++) { double dx = 0; dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen; dx += dPhase; double dy = Math.Sin(dx); int nOldX = 0, nOldY = 0; nOldX = bXDir ? i + (int)(dy * dMultValue) : i; nOldY = bXDir ? j : j + (int)(dy * dMultValue); Color color = srcBmp.GetPixel(i, j); if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height) { destBmp.SetPixel(nOldX, nOldY, color); } } } srcBmp.Dispose(); return destBmp; } #endregion } }
The above is the detailed content of Complete sample code sharing for C# to generate beautiful verification code. For more information, please follow other related articles on the PHP Chinese website!

如何使用C#编写时间序列预测算法时间序列预测是一种通过分析过去的数据来预测未来数据趋势的方法。它在很多领域,如金融、销售和天气预报中有广泛的应用。在本文中,我们将介绍如何使用C#编写时间序列预测算法,并附上具体的代码示例。数据准备在进行时间序列预测之前,首先需要准备好数据。一般来说,时间序列数据应该具有足够的长度,并且是按照时间顺序排列的。你可以从数据库或者

如何使用Redis和C#开发分布式事务功能引言分布式系统的开发中,事务处理是一项非常重要的功能。事务处理能够保证在分布式系统中的一系列操作要么全部成功,要么全部回滚。Redis是一种高性能的键值存储数据库,而C#是一种广泛应用于开发分布式系统的编程语言。本文将介绍如何使用Redis和C#来实现分布式事务功能,并提供具体代码示例。I.Redis事务Redis

如何实现C#中的人脸识别算法人脸识别算法是计算机视觉领域中的一个重要研究方向,它可以用于识别和验证人脸,广泛应用于安全监控、人脸支付、人脸解锁等领域。在本文中,我们将介绍如何使用C#来实现人脸识别算法,并提供具体的代码示例。实现人脸识别算法的第一步是获取图像数据。在C#中,我们可以使用EmguCV库(OpenCV的C#封装)来处理图像。首先,我们需要在项目

如何使用C#编写动态规划算法摘要:动态规划是求解最优化问题的一种常用算法,适用于多种场景。本文将介绍如何使用C#编写动态规划算法,并提供具体的代码示例。一、什么是动态规划算法动态规划(DynamicProgramming,简称DP)是一种用来求解具有重叠子问题和最优子结构性质的问题的算法思想。动态规划将问题分解成若干个子问题来求解,通过记录每个子问题的解,

Redis在C#开发中的应用:如何实现高效的缓存更新引言:在Web开发中,缓存是提高系统性能的常用手段之一。而Redis作为一款高性能的Key-Value存储系统,能够提供快速的缓存操作,为我们的应用带来了不少便利。本文将介绍如何在C#开发中使用Redis,实现高效的缓存更新。Redis的安装与配置在开始之前,我们需要先安装Redis并进行相应的配置。你可以

C#开发中如何处理跨域请求和安全性问题在现代的网络应用开发中,跨域请求和安全性问题是开发人员经常面临的挑战。为了提供更好的用户体验和功能,应用程序经常需要与其他域或服务器进行交互。然而,浏览器的同源策略导致了这些跨域请求被阻止,因此需要采取一些措施来处理跨域请求。同时,为了保证数据的安全性,开发人员还需要考虑一些安全性问题。本文将探讨C#开发中如何处理跨域请

如何实现C#中的图像压缩算法摘要:图像压缩是图像处理领域中的一个重要研究方向,本文将介绍在C#中实现图像压缩的算法,并给出相应的代码示例。引言:随着数字图像的广泛应用,图像压缩成为了图像处理中的重要环节。压缩能够减小存储空间和传输带宽,并能提高图像处理的效率。在C#语言中,我们可以通过使用各种图像压缩算法来实现对图像的压缩。本文将介绍两种常见的图像压缩算法:

如何在C#中实现遗传算法引言:遗传算法是一种模拟自然选择和基因遗传机制的优化算法,其主要思想是通过模拟生物进化的过程来搜索最优解。在计算机科学领域,遗传算法被广泛应用于优化问题的解决,例如机器学习、参数优化、组合优化等。本文将介绍如何在C#中实现遗传算法,并提供具体的代码示例。一、遗传算法的基本原理遗传算法通过使用编码表示解空间中的候选解,并利用选择、交叉和


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
