程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 12306奇葩驗證碼激發思慮之C#完成驗證碼法式

12306奇葩驗證碼激發思慮之C#完成驗證碼法式

編輯:C#入門知識

12306奇葩驗證碼激發思慮之C#完成驗證碼法式。本站提示廣大學習愛好者:(12306奇葩驗證碼激發思慮之C#完成驗證碼法式)文章只能為提供參考,不一定能成為您想要的結果。以下是12306奇葩驗證碼激發思慮之C#完成驗證碼法式正文


近日鐵路訂票網“12306”又湧現多道另類考題,竟要訂票者在8個圖案中“點擊圖中一切美須眉”、“請點擊下圖中一切的非智能眼鏡”、“請點擊下圖中一切的博斯普魯斯海峽”,網友吐槽:比高考題還難,究竟是甚麼模樣的,先跟年夜家分享一下幾個例子:

哈哈,是有點奇葩的驗證碼,怪不得有人會說“媽媽我曾經找不到回家”,這讓爭分奪秒的春運網上搶票者剎時傻眼,九成網友曾經被打敗……

正巧小編比來也在研討驗證碼,參考了很多網上案例,整頓了一篇文章特分享給年夜家。

驗證碼的普通編寫思緒為:
       1.界說驗證碼字符長度;
       2.依據長度隨機生成驗證碼字符串;
       3.將驗證碼字符串轉換成圖片情勢,並在圖片中生成隨機噪聲點和聲線(對驗證碼停止隱約辨認處置);
       4.顯示成果。

 ///
 /// 生成隨機驗證碼
 ///
 /// 驗證碼長度
 ///
 public string CreateIdentifyingCode(int CodeLen)
 {
 if (CodeLen < 1)
  return String.Empty;
 int num;
 string checkcode = String.Empty;
 Random random = new Random();
 for (int index = 0; index < CodeLen; index++)
 {
  num = random.Next();
  if (num % 2 == 0)
  checkcode += (char)('0' + (char)(num % 10));
  else
  checkcode += (char)('A' + (char)(num % 26));
 }
 return checkcode;
 }
-------------------------------------------------------------------------------------------------
 ///
 /// 生成驗證碼圖片
 ///
 ///
 /// 
 private void CreateCheckCodeImage(string checkcode)
 {
  if (checkcode == null || checkcode.Trim() == String.Empty)
  return;
  //創立圖片年夜小
  System.Drawing.Bitmap image = new  System.Drawing.Bitmap((int)Math.Ceiling(checkcode.Length*12.5),22);
  //創立畫板
  Graphics graphic = Graphics.FromImage(image);
 
  try
  {
  Random random = new Random();
  graphic.Clear(Color.White);
  int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
  //繪圖片配景噪聲線
  for (int index = 0; index < 25; index++)
  {
   x1 = random.Next(image.Width);
   y1 = random.Next(image.Height);
   x2 = random.Next(image.Width);
   y2 = random.Next(image.Height);
   graphic.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2);
  }
  Font font = new System.Drawing.Font("Helvetica", 12, (FontStyle.Bold |FontStyle.Italic));
  LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),Color.Blue,Color.DarkBlue,1.2f,true);
  graphic.DrawString(checkcode,font,brush,2,2);
 
  int x = 0;
  int y = 0;
  // 繪圖片的遠景噪聲點
  for (int index = 0; index < 100; index++)
  {
   x = random.Next(image.Width);
   y = random.Next(image.Height);
   image.SetPixel(x,y,Color.FromArgb(random.Next()));
  }
  //繪圖片的邊框線
  graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
  //網頁呼應
  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
  Response.ClearContent();
  Response.ContentType = "image/Gif";
  Response.BinaryWrite(ms.ToArray());
  }
  finally
  {
  graphic.Dispose();
  image.Dispose();
  }
 }

以上所生成的為簡略的驗證碼。接上去我從其他的博客中進修了其他情勢的後果。

/* 圖片畫線特別後果:貝塞爾曲線 */
  Graphics graph = Graphics.FromImage(image);
  graph.Clear(Color.WhiteSmoke);
  Point[] myArray ={
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50)),
     new Point(random.Next(150),random.Next(50))
    };
  Pen myPen = new Pen(Color.Blue, 1);
  GraphicsPath myPath = new GraphicsPath();
  myPath.AddBeziers(myArray);
  graph.DrawPath(myPen, myPath);

驗證碼字符色彩變換後果:完成該後果,我們起首來界說一個色彩聚集,然後經由過程for輪回使其隨機轉變字體色彩則可。

 #region 界說色彩數組
 Color[] colors = { Color.Blue, Color.Green, Color.Red, Color.Gold, Color.Black, Color.Chocolate, Color.Orange, Color.Purple };
 public Color[] Colors
 {
  get { return colors; }
  set { colors = value; }
 }
 #endregion
 Brush brush;
 int colornum;
 for(int i=0; i
 {
  colornum = random.Next(Colors.Length - 1);
  brush = new System.Drawing.SolidBrush(Colors[cindex]);
 
  //應用DrawString函數停止色彩填充便可以了。
 }

 異樣的道理我們也能夠界說一個字體的數組來停止驗證碼字體切換。代碼和色彩的相似,這裡就不加以包袱。
接上去看看若何使得驗證碼的字體停止歪曲。

private const double PI = 3.1415926535897932384626433832795;
 private const double PI2 = 6.283185307179586476925286766559;
 ///
 /// 波形濾鏡後果函數
 ///
 ///
 ///
 ///
 ///
 ///
 public System.Drawing.Bitmap TwistImage(Bitmap srcbmp, double dmultvalue, double dphase)
 {
  System.Drawing.Bitmap destbmp = new Bitmap(srcbmp.Width,srcbmp.Height);
  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 dbaselen = (double)destbmp.Width;
  for (int i = 0; i < destbmp.Width; i++)
  {
  for (int j = 0; j < destbmp.Height; j++)
  {
   double dx = 0;
   dx = (PI2 * (double)j) / dbaselen;
   dx += dphase;
 
   double dy = Math.Sin(dx);
 
   int noldx = 0, noldy = 0;
   noldx = i + (int)(dy * dmultvalue);
   noldy = 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;
 }

下面代碼是參考了這段代碼停止的進修<C#.net 好用的驗證碼代碼 漢字-變色-歪曲-動搖 >,代碼以下


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class study_CheckCode2 : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 string code = CreateVerifyCode();  //取隨機碼
 CreateImageOnPage(code, this.Context); // 輸入圖片
 Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper()));// 應用Cookies取驗證碼的值
 }

 #region 驗證碼長度(默許4個驗證碼的長度)
 int length = 4;
 public int Length
 {
 get { return length; }
 set { length = value; }
 }
 #endregion

 #region 驗證碼字體年夜小(為了顯示歪曲後果,默許40像素,可以自行修正)
 int fontSize = 40;
 public int FontSize
 {
 get { return fontSize; }
 set { fontSize = value; }
 }
 #endregion

 #region 邊框補(默許1像素)
 int padding = 2;
 public int Padding
 {
 get { return padding; }
 set { padding = value; }
 }
 #endregion

 #region 能否輸入燥點(默許不輸入)
 bool chaos = true;
 public bool Chaos
 {
 get { return chaos; }
 set { chaos = value; }
 }
 #endregion

 #region 輸入燥點的色彩(默許灰色)
 Color chaosColor = Color.LightGray;
 public Color ChaosColor
 {
 get { return chaosColor; }
 set { chaosColor = value; }
 }
 #endregion

 #region 自界說配景色(默許白色)
 Color backgroundColor = Color.White;
 public Color BackgroundColor
 {
 get { return backgroundColor; }
 set { backgroundColor = value; }
 }
 #endregion

 #region 自界說隨機色彩數組
 Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
 public Color[] Colors
 {
 get { return colors; }
 set { colors = value; }
 }
 #endregion

 #region 自界說字體數組
 string[] fonts = { "Arial", "Georgia" };
 public string[] Fonts
 {
 get { return fonts; }
 set { fonts = value; }
 }
 #endregion

 #region 自界說隨機碼字符串序列(應用逗號分隔)
 //string codeSerial = "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,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 codeSerial = "阿,保,持,的,法,規,和,東,三,省,問,我,惹,你,诶,沒,改,變,揍,屁,股,吧";
 public string CodeSerial
 {
 get { return codeSerial; }
 set { codeSerial = value; }
 }
 #endregion

 #region 發生波形濾鏡後果

 private const double PI = 3.1415926535897932384626433832795;
 private const double PI2 = 6.283185307179586476925286766559;

 /// <summary>
 /// 正弦曲線Wave歪曲圖片(Edit By 51aspx.com)
 /// </summary>
 /// <param name="srcBmp">圖片途徑</param>
 /// <param name="bXDir">假如歪曲則選擇為True</param>
 /// <param name="dMultValue">波形的幅度倍數,越年夜歪曲的水平越高,普通為3</param>
 /// <param name="dPhase">波形的肇端相位,取值區間[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);

 // 將位圖配景填充為白色
 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);

  // 獲得以後點的色彩
  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;
 }
 #endregion

 #region 生成校驗碼圖片
 public Bitmap CreateImageCode(string code)
 {
 int fSize = FontSize;
 int fWidth = fSize + Padding;

 int imageWidth = (int)(code.Length * fWidth) + 30 + Padding * 2;
 int imageHeight = fSize * 2 + Padding;

 System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

 Graphics g = Graphics.FromImage(image);

 g.Clear(BackgroundColor);

 Random rand = new Random();

 //給配景添加隨機生成的燥點
 if (this.Chaos)
 {

  Pen pen = new Pen(ChaosColor, 0);
  int c = Length * 10;

  for (int i = 0; i < c; i++)
  {
  int x = rand.Next(image.Width);
  int y = rand.Next(image.Height);

  g.DrawRectangle(pen, x, y, 1, 1);
  }
 }

 int left = 0, top = 0, top1 = 1, top2 = 1;

 int n1 = (imageHeight - FontSize - Padding * 2);
 int n2 = n1 / 4;
 top1 = n2;
 top2 = n2 * 2;

 Font f;
 Brush b;

 int cindex, findex;

 //隨機字體和色彩的驗證碼字符
 for (int i = 0; i < code.Length; i++)
 {
  cindex = rand.Next(Colors.Length - 1);
  findex = rand.Next(Fonts.Length - 1);

  f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
  b = new System.Drawing.SolidBrush(Colors[cindex]);

  if (i % 2 == 1)
  {
  top = top2;
  }
  else
  {
  top = top1;
  }

  left = i * fWidth;

  g.DrawString(code.Substring(i, 1), f, b, left, top);
 }

 //畫一個邊框 邊框色彩為Color.Gainsboro
 g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
 g.Dispose();

 //發生波形(Add By 51aspx.com)
 image = TwistImage(image, true, 8, 4);

 return image;
 }
 #endregion

 #region 將創立好的圖片輸入到頁面
 public void CreateImageOnPage(string code, HttpContext context)
 {
 System.IO.MemoryStream ms = new System.IO.MemoryStream();
 Bitmap image = this.CreateImageCode(code);

 image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

 context.Response.ClearContent();
 context.Response.ContentType = "image/Jpeg";
 context.Response.BinaryWrite(ms.GetBuffer());

 ms.Close();
 ms = null;
 image.Dispose();
 image = null;
 }
 #endregion

 #region 生成隨機字符碼
 public string CreateVerifyCode(int codeLen)
 {
 if (codeLen == 0)
 {
  codeLen = Length;
 }

 string[] arr = CodeSerial.Split(',');

 string code = "";

 int randValue = -1;

 Random rand = new Random(unchecked((int)DateTime.Now.Ticks));

 for (int i = 0; i < codeLen; i++)
 {
  randValue = rand.Next(0, arr.Length - 1);

  code += arr[randValue];
 }

 return code;
 }
 public string CreateVerifyCode()
 {
 return CreateVerifyCode(0);
 }
 #endregion

}

一年一度的搶票高潮又開端了,願望年夜家都能順遂買到回家的火車篇,回家過年,忽然感到有點年味了,一年又一年,時光都去哪了,小小的感歎一下……

言歸正傳,這就是為年夜家分享的C#驗證碼法式,和12306驗證碼差多了,不外也是小編的進修收成吧!年夜家也能夠聯合上面這兩篇文章停止進修:

《12306靜態驗證碼啟示之ASP.NET完成靜態GIF驗證碼(附源碼)》

《12306驗證碼破解思緒分享》

願望本文所述對年夜家進修驗證碼技巧有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved