为了防止 对方用代码 瘫痪 注册页面, 有时要用到验证码识别 人还是代码 在填写你的网页。
Step1: 创建一个web 应用
Step2: 进入创建的应用的后部代码
Step3: 添加 Namespace for drawing Image.
using System.Drawing;
using System.Drawing.Imaging;
Step4: // 定义随机产生4个数字
Code
public static string GetRandomPassword()
{
Random rand = new Random();
System.Text.StringBuilder password = new System.Text.StringBuilder(4);
for (int i = 1; i <= length; i++)
{ int charIndex;
do { charIndex = rand.Next(48, 123); }
while (!(charIndex >= 48 && charIndex <= 57));
password.Append(Convert.ToChar(charIndex)); }
return password.ToString(); }
Step5: //把上面的数字转换成图片
Code
1 private void GenerateImage(string strRegistrationStr)
2 {
3 Bitmap objBitmap = new Bitmap(150, 30);
4 Graphics objGraphics = Graphics.FromImage(objBitmap);
5 SolidBrush objForeColor = new SolidBrush(Color.White);
6 SolidBrush objBackColor = new SolidBrush(Color.Black);
7 objGraphics.FillRectangle(objBackColor, 0, 0, 150, 30);
8 Font objFont = new Font("Arial", 15);
9 Point objPoint = new Point(5, 5);
10 objGraphics.DrawString(strRegistrationStr, objFont, objForeColor, objPoint);
11 //保存图片
12 //或直接不保存objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
13 objBitmap.Save(Server.MapPath("zhuchetu.gif"), ImageFormat.Gif);
14 if(objBitmap != null)
15 objBitmap.Dispose();
16 if (objGraphics != null)
17 objGraphics.Dispose();
18 }
19
Step6: 最后代码调用这个
Code
protected void btnzhutu_Click(object sender, EventArgs e)
{
GenerateImage(GetRandomPassword());
ImgRegistrationStr.ImageUrl = "zhuchetu.gif";
}