- using System;
- using System.Data;
- using System.Configuration;
- 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;
- /// <summary>
- /// VerifyCode 的摘要说明 产生随机数
- /// </summary>
- public class VerifyCode
- {
- public VerifyCode()
- {
- }
- //产生随机字符串
- /// <summary>
- /// 产生随机数
- /// </summary>
- /// <param name="num">需要的字符的个数</param>
- /// <returns>返回产生的随机数</returns>
- public string GenCode(int num)
- {
- //定义一个数组
- string[] source ={"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"};
- //定义一个装数组的字符串
- string code = "";
- Random rd = new Random();
- for (int i = 0; i < num; i++)
- {
- code += source[rd.Next(0, source.Length)];
- }
- return code;//返回产生的随机数
- }
- //生成图片
- public void GenImg(string code, Page curPage)
- {
- Bitmap myPalette = new Bitmap(60, 20);//定义一个画板
- Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例
- Rectangle rc = new Rectangle(0, 0, 60, 20);//定义一个矩形
- gh.FillRectangle(new SolidBrush(Color.Blue), rc);//填充矩形
- gh.DrawString(code, new Font("宋体", 16), new SolidBrush(Color.White), rc);//在矩形内画出字符串
- myPalette.Save(curPage.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
- curPage.Session["ValidateCode"] = code;//将字符串保存到Session中,以便需要时进行验证
- gh.Dispose();//关闭
- myPalette.Dispose();
- }
- }
NET 很简单的一个生成随机验证码封装的一个类
最新推荐文章于 2019-02-25 15:43:06 发布