新手,今天注册时发现的问题
注册时,有个验证码,是随即的4个汉字不会是所有的汉字,然后random的吧?那怎么实现啊?
/// <summary> /// 生成一个随机文字图片 /// </summary> /// <param name="count">图片中字的个</param> /// <returns>生成的文字</returns> public void CreateImage(int count) { string ValidCode = GenCode(count); CreateCheckCodeImage(ValidCode); HttpContext.Current.Session["ValidCode"] = ValidCode; } /// <summary> /// 产生随机字符串 /// </summary> /// <param name="num">随机出几个字符</param> /// <returns>随机出的字符串</returns> private string GenCode(int num) { //此处可以定义一些汉字,一般会写很多. string str = "巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌"; char[] chastr = str.ToCharArray(); string code = ""; Random rd = new Random(); int i; for (i = 0; i < num; i++) { code += str.Substring(rd.Next(0, str.Length), 1); } return code; } /// <summary> /// 生成图片(增加背景噪音线、前景噪音点) /// </summary> /// <param name="checkCode">随机出字符串</param> private void CreateCheckCodeImage(string checkCode) { if (checkCode.Trim() == "" || checkCode == null) return; System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 21.5), 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); // 画图片的背景噪音线 int i; for (i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true); g.DrawString(checkCode, font, brush, 2, 2); //画图片的前景噪音点 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); ms = new (); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ContentType = "image/Gif"; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); } catch { g.Dispose(); image.Dispose(); } } 调用时:CreateImage(4);就可以了