程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 簡易生成注冊碼(數字+大小寫字母)

asp.net 簡易生成注冊碼(數字+大小寫字母)

編輯:ASP.NET基礎

如果有哪裡看不懂的,請留言哦

生成隨機碼類:SigowayRandom.cs 
復制代碼 代碼如下:
using System;
namespace RongYi.Model.Common
{
/// <summary>
/// SigowayRandom 的摘要說明
/// </summary>
public class SigowayRandom
{
#region 獲取校驗碼

/// <summary>
/// 獲取校驗碼
/// </summary>
/// <returns>校驗碼字符數組</returns>
public static string[] GetCheckCode()
{
string[] strCheckCode = new string[4];

// 已系統時間毫秒為隨機種子
int nSeed = Convert.ToInt16(DateTime.Now.Millisecond);
Random random = new Random(nSeed);

// 產生0-9隨機數
strCheckCode[0] = Convert.ToString(random.Next(1, 10));
// 產生a-z、A-Z隨機字母
strCheckCode[1] = SigowayRandom.GetLetter(random);
strCheckCode[2] = Convert.ToString(random.Next(1, 10));
strCheckCode[3] = SigowayRandom.GetLetter(random);

// 返回校驗碼
return strCheckCode;
}

#endregion

#region 獲取字母,區分大小寫

/// <summary>
/// 獲取字母,區分大小寫
/// </summary>
/// <returns>大小寫字母</returns>
private static string GetLetter(Random random)
{
// 隨機數
int nChar = random.Next(65, 122);

// 非字母ASCII段
if (nChar >= 91 && nChar <= 96)
{
nChar -= 6;
}

return Convert.ToString((char)nChar);
}

#endregion
}
}


繪制校驗碼類:SigowayDraw.cs
復制代碼 代碼如下:
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;

namespace RongYi.Model.Common
{
/// <summary>
/// SigowayDraw 的摘要說明
/// </summary>
public class SigowayDraw
{
#region 構造方法

/// <summary>
/// 構造方法
/// </summary>
public SigowayDraw() { }

#endregion

#region 畫校驗碼

/// <summary>
/// 畫校驗碼
/// </summary>
/// <returns>校驗碼</returns>
public string DrawString()
{
// 設置字體
Font drawFont = new Font("Arial", 10);
// 創建位圖元素
Bitmap objBitmap = new Bitmap(50, 20);
// 創建畫圖對象
Graphics objGraphics = Graphics.FromImage(objBitmap);
// 設置畫布背景色
objGraphics.Clear(Color.White);
// 獲取隨機字符串
string[] strDrawString = SigowayRandom.GetCheckCode();

// 畫字符串
objGraphics.DrawString(strDrawString[0], drawFont, new SolidBrush(Color.Purple), 1, 2);
objGraphics.DrawString(strDrawString[1], drawFont, new SolidBrush(Color.Green), 12, 2);
objGraphics.DrawString(strDrawString[2], drawFont, new SolidBrush(Color.Red), 24, 2);
objGraphics.DrawString(strDrawString[3], drawFont, new SolidBrush(Color.SteelBlue), 35, 2);

// 畫干擾線
objGraphics.DrawLine(Pens.Silver, 5, 10, 40, 3);
objGraphics.DrawLine(Pens.Gray, 10, 5, 45, 15);
objGraphics.DrawLine(Pens.HotPink, 15, 20, 30, 10);
objGraphics.DrawLine(Pens.LightPink, 10, 15, 35, 20);

// 把圖像畫到位圖對象中
objGraphics.DrawImage(objBitmap, 0, 0);

// 設置保存圖片路徑及名字
string strFile = HttpRuntime.AppDomainAppPath.ToString() + "/Resource/img/CheckCode.gif";

// 輸出文件
objBitmap.Save(strFile, ImageFormat.Gif);

// 連接校驗碼字符串
string strCheckCode = string.Empty;
foreach (string strTemp in strDrawString)
{
strCheckCode += strTemp;
}

// 返回校驗碼
return strCheckCode;
}

#endregion
}
}

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