コード例 #1
0
        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private Bitmap CreateImageCode(string code)
        {
            int      fSize       = FontSize;
            int      fWidth      = fSize + Padding;
            int      imageWidth  = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int      imageHeight = fSize * 2 + Padding;
            Bitmap   image       = new Bitmap(imageWidth, imageHeight);
            Graphics g           = Graphics.FromImage(image);

            g.Clear(BackgroundColor);
            Random rand = new Random();

            //给背景添加随机生成的燥点
            if (this.UsingChaos)
            {
                Pen pen = new Pen(ChaosColor, 0);
                int c   = Length * 10;
                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);
                }
            }
            int left = 0, top = 0, top1 = 1, top2 = 1;
            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;
            Font  f;
            Brush b;
            int   cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rand.Next(Colors.Length - 1);
                findex = rand.Next(Fonts.Length - 1);
                f      = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b      = new System.Drawing.SolidBrush(Colors[cindex]);
                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }
                left = i * fWidth;
                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }
            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();
            //产生波形
            if (UsingTwist)
            {
                image = GDIHelper.TwistImage(image, true, 8, 4);
            }
            return(image);
        }