在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
随便建个aspx页面,前台不需任何处理,后台代码如下:
Default2 : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e) { string checkCode = CreateRandomCode(4); Session["CheckCode"] = checkCode; CreateImage(checkCode); } private string CreateRandomCode(int codeCount) { // 函数功能:产生数字和字符混合的随机字符串 string allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] allCharArray = allChar.ToCharArray(); string randomCode = ""; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { int r=rand.Next(61); randomCode+=allCharArray.GetValue(r); } return randomCode; } private void CreateImage(string checkCode) { // 生成图象验证码函数 int iwidth = (int)(checkCode.Length * 11.5); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20); Graphics g = Graphics.FromImage(image); Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold); Brush b = new System.Drawing.SolidBrush(Color.Azure);//字母白色 //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(Color.Brown);//背景灰色 g.DrawString(checkCode, f, b, 3, 3); Pen blackPen = new Pen(Color.Black, 0); Random rand = new Random(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); } }
用个Image控件ImageURL绑定这个aspx文件就ok啦,很简单,实用。代码相应的可以修改。 如果想实现无刷新的更换验证图片 在页面中加个脚本 |
请发表评论