C#随机生成验证码图

在书上学到绘图验证码示例,记录一下

//生成验证码
        public string CheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;//声明变量存储随机生成的4位英文或数字
            Random random = new Random();   //生成随机数
            for(int i = 0; i < 4; i++)
            {
                number = random.Next();     //返回非负随机数
                if (number % 2 == 0)        //判断数字是否为偶数
                {
                    code = (char)('0' + (char)(number % 10));
                }
                else                        
                {
                    code = (char)('A' + (char)(number % 26));
                }
                checkCode +=" "+ code.ToString();
            }
            return checkCode;
        }
        private void CodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }
            Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 9.5)), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                Random random = new Random();           //生成随机生成色
                g.Clear(Color.White);                   //清空图片背景色
                for (int i = 0; i < 3; 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);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold));
                g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);
                for(int i = 0; i < 150; i++)            //画图片前景噪音点
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                this.pictureBox1.Width = image.Width;
                this.pictureBox1.Height = image.Height;
                this.pictureBox1.BackgroundImage = image;
            }
            catch
            {

            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章