/// <summary> /// 生成校验码图片。 /// </summary> /// <param name="code">验证码文本。</param> /// <returns></returns> public static System.Drawing.Bitmap GenerateVerifyCodeImage(string code) { int fSize = VerifyCode.FontSize; int iPadding = VerifyCode.Padding; int fWidth = fSize + iPadding; int imageWidth = code.Length * fWidth + iPadding * 2 + fWidth; int imageHeight = fSize * 2 + iPadding; System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); g.Clear(VerifyCode.BackColor); System.Random rand = new System.Random(); int left, top, top1, top2; int n1 = (imageHeight - fSize - iPadding * 2); int n2 = n1 / 4; top1 = n2; top2 = n2 * 2; System.Drawing.Font f; System.Drawing.Brush b; int cindex, findex; #region 随机字体和颜色的验证码字符 cindex = rand.Next(ForeColors.Length); for (int i = 0; i < code.Length; i++) { findex = rand.Next(Fonts.Length); f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold); b = new System.Drawing.SolidBrush(ForeColors[cindex]); if (i % 2 == 1) { top = top2; } else { top = top1; } left = i * fWidth; g.DrawString(code.Substring(i, 1), f, b, left, top); } #endregion //#region 给背景添加随机生成的燥点 //if (VerifyCode.HasPinto && VerifyCode.Pinto > 0) //{ // //System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.LightGray, 0); // System.Drawing.Pen pen = new System.Drawing.Pen(VerifyCode.BackColor, 0); // int c = System.Convert.ToInt32(image.Width * image.Height * VerifyCode.Pinto); // for (int i = 0; i < c; i++) // { // int x = rand.Next(image.Width); // int y = rand.Next(image.Height); // g.DrawRectangle(pen, x, y, 1, 1); // } //} //#endregion //画一个边框 边框颜色为Color.Gainsboro //g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1); g.Dispose(); //产生波形 if (VerifyCode.BendingAngle != 0) { image = VerifyCode.TwistImage(image, VerifyCode.BackColor, true, VerifyCode.BendingAngle, 4); } DrawCurve(image, VerifyCode.ForeColors[rand.Next(0, VerifyCode.ForeColors.Length)]); return(image); }