.net生成验证码

//驗證碼
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace Alumni.Manage
{
 /// <summary>
 /// VerifyCode 的摘要说明。
 /// </summary>
 public class VerifyCode : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   //RndNum是一个自定义函数
   string VNum=RndNum(4); //这里的数字4代表显示的是4位的验证字符串!
   Session["VNum"] = VNum;
   ValidateCode(VNum);
  }

  private void ValidateCode(string VNum)
  {
   int Gheight=(int)(VNum.Length * 11.5);
   //gheight为图片宽度,根据字符长度自动更改图片宽度
   System.Drawing.Bitmap Img = new System.Drawing.Bitmap(Gheight,20);
   Graphics g = Graphics.FromImage(Img);
   g.DrawString(VNum,new System.Drawing.Font("Arial",10),new System.Drawing.SolidBrush(Color.Red),3,3);
   //在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y)
   System.IO.MemoryStream ms=new System.IO.MemoryStream();
   Img.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
   Response.ClearContent(); //需要输出图象信息 要修改HTTP头
   Response.ContentType="image/Png";
   Response.BinaryWrite(ms.ToArray());
   g.Dispose();
   Img.Dispose();
   Response.End();
  }

  public string RndNum(int VcodeNum)
  {
   string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   string  VNum = "" ;
   int l = 0;
   Random rand =new Random();
   for(int i=1;i<VcodeNum+1;i++)
   {
    l = rand.Next(chars.Length);
    VNum += chars[l];
   }
   return VNum ;
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值