C implementation of a more beautiful verification code complete example

  • 2021-10-16 02:27:57
  • OfStack

This paper describes an example of C # to achieve a more beautiful verification code. Share it for your reference, as follows:


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
public partial class ValidateCode : System.Web.UI.Page
{
 private int letterWidth = 16;// Width range of a single font 
 private int letterHeight = 22;// Height range of a single font 
 private int letterCount = 4;// Verification code number 
 private char[] chars = "0123456789".ToCharArray();
 private string[] fonts = { "Arial", "Georgia" };
 /// <summary>
 ///  Generate waveform filter effect 
 /// </summary>
 private const double PI = 3.1415926535897932384626433832795;
 private const double PI2 = 6.283185307179586476925286766559;
 protected void Page_Load(object sender, EventArgs e)
 {
  // Prevent Web pages from falling back -- Disable caching 
  Response.Expires = 0;
  Response.Buffer = true;
  Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
  Response.AddHeader("pragma", "no-cache");
  Response.CacheControl = "no-cache";
  string str_ValidateCode = GetRandomNumberString(letterCount);
  HttpCookie objCookie = new HttpCookie("ValidateCode");
  objCookie.Value = str_ValidateCode;
  objCookie.Path = "/";
  objCookie.Expires = DateTime.Now.AddSeconds(1200);
  Response.Cookies.Add(objCookie);
  CreateImage(str_ValidateCode);
 }
 public void CreateImage(string checkCode)
 {
  int int_ImageWidth = checkCode.Length * letterWidth;
  Random newRandom = new Random();
  Bitmap image = new Bitmap(int_ImageWidth, letterHeight);
  Graphics g = Graphics.FromImage(image);
  // Generate random generator 
  Random random = new Random();
  // White background 
  g.Clear(Color.White);
  // Draw the background noise line of the picture 
  for (int i = 0; i < 10; i++)
  {
   int x1 = random.Next(image.Width);
   int x2 = random.Next(image.Width);
   int y1 = random.Next(image.Height);
   int y2 = random.Next(image.Height);
   g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
  }
  // Noise points in the foreground of drawing pictures 
  for (int i = 0; i < 10; i++)
  {
   int x = random.Next(image.Width);
   int y = random.Next(image.Height);
   image.SetPixel(x, y, Color.FromArgb(random.Next()));
  }
  // Verification code characters with random fonts and colors 
  int findex;
  for (int int_index = 0; int_index < checkCode.Length; int_index++)
  {
   findex = newRandom.Next(fonts.Length - 1);
   string str_char = checkCode.Substring(int_index, 1);
   Brush newBrush = new SolidBrush(GetRandomColor());
   Point thePos = new Point(int_index * letterWidth + 1 + newRandom.Next(3), 1 + newRandom.Next(3));//5+1+a+s+p+x
   g.DrawString(str_char, new Font(fonts[findex], 12, FontStyle.Bold), newBrush, thePos);
  }
  // Gray border 
  g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));
  // Picture distortion 
  //image = TwistImage(image, true, 3, 4);
  // Send the generated picture back to the client 
  MemoryStream ms = new MemoryStream();
  image.Save(ms, ImageFormat.Png);
  Response.ClearContent(); // Need to output image information   To modify HTTP Head 
  Response.ContentType = "image/Png";
  Response.BinaryWrite(ms.ToArray());
  g.Dispose();
  image.Dispose();
 }
 /// <summary>
 ///  Sinusoidal curve Wave Distorted picture 
 /// </summary>
 /// <param name="srcBmp"> Picture path </param>
 /// <param name="bXDir"> If it is distorted, select True</param>
 /// <param name="nMultValue"> The larger the amplitude multiple of the waveform, the higher the degree of distortion, 1 Be general 3</param>
 /// <param name="dPhase"> Initial phase and value interval of waveform [0-2*PI)</param>
 /// <returns></returns>
 public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
 {
  System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
  //  Fill the bitmap background with white 
  System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
  graph.FillRectangle(new SolidBrush(System.Drawing.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 ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
    dx += dPhase;
    double dy = Math.Sin(dx);
    //  Gets the color of the current point 
    int nOldX = 0, nOldY = 0;
    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
    nOldY = bXDir ? j : j + (int)(dy * dMultValue);
    System.Drawing.Color color = srcBmp.GetPixel(i, j);
    if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
    {
     destBmp.SetPixel(nOldX, nOldY, color);
    }
   }
  }
  return destBmp;
 }
 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(210);
  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);// 5+1+a+s+p+x
 }
 //  Generate random number strings 
 public string GetRandomNumberString(int int_NumberLength)
 {
  Random random = new Random();
  string validateCode = string.Empty;
  for (int i = 0; i < int_NumberLength; i++)
   validateCode += chars[random.Next(0, chars.Length)].ToString();
  return validateCode;
 }
}


<img alt=" Can't see clearly, change 1 Zhang " title=" Can't see clearly, change 1 Zhang " src="ValidateCode.aspx" style="cursor:pointer" onclick="this.src=this.src+'?r='+Math.random()" />

For more readers interested in C # related content, please check the topics on this site: "Summary of XML File Operation Skills in C #", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: