C#制作验证码

 void CodeImage(string code)
        {
            if (code == null || code.Trim() == string.Empty)
                return;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(code.Length * 11.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                Random rdm = new Random();
                g.Clear(Color.White);
                //画图片的背景噪音线 
                for (int i = 0; i < 3; i++)
                {
                    int x1 = rdm.Next(image.Width);
                    int x2 = rdm.Next(image.Width);
                    int y1 = rdm.Next(image.Height);
                    int y2 = rdm.Next(image.Height);
                    g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, FontStyle.Bold);
                g.DrawString(code, font, new SolidBrush(Color.Red), 2, 2);
                //画前景噪音线 
                for (int i = 0; i < 150; i++)
                {
                    int x = rdm.Next(image.Width);
                    int y = rdm.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(rdm.Next()));
                }
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                pictureBox1.Width = image.Width;
                pictureBox1.Height = image.Height;
                pictureBox1.Image = image;
            }
            catch
            { }
        }
原文地址:https://www.cnblogs.com/zhayunjia/p/4900990.html