📄 randomnumber.aspx.cs
字号:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
public partial class RandomNumber : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string str_ValidateCode = GetRandomNumberString(4);
Session["ValidateCode"] = str_ValidateCode;
CreateImage(str_ValidateCode);
}
}
public string GetRandomNumberString(int int_NumberLength)
{
string str_Number = string.Empty;
string temp = "";
string[] source ={"1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"P","Q","R","S","T","U","V","W","X","Y","Z"};
Random rd = new Random();
for (int int_index = 0; int_index < int_NumberLength; int_index++)
{
str_Number += source[rd.Next(0, source.Length)];
}
return str_Number;
}
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(0, 120);
int int_Green = RandomNum_Sencond.Next(0, 120);
int int_Blue = (int_Red + int_Green > 400) ? 400 - int_Red - int_Green : 0;
int_Blue = (int_Blue > 255) ? 120 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
public void CreateImage(string str_ValidateCode)
{
int int_ImageWidth = str_ValidateCode.Length * 15;
Random newRandom = new Random();
Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
Graphics theGraphics = Graphics.FromImage(theBitmap);
theGraphics.Clear(Color.Bisque);
theGraphics.DrawRectangle(new Pen(Color.Red, 1), 0, 0, int_ImageWidth - 1, 19);
Font theFont = new Font("Arial", 10);
for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
{
string str_char = str_ValidateCode.Substring(int_index, 1);
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
theGraphics.DrawString(str_char, theFont, newBrush, thePos);
}
MemoryStream ms = new MemoryStream();
theBitmap.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
theGraphics.Dispose();
theBitmap.Dispose();
Response.End();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -