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
            {

            }
        }

 

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