Learning notes: using GDI + to generate a simple verification code image, learning notes gdi
Learning notes: Use GDI + to generate a simple verification code Image
1 /// <summary> 2 /// when you click the image, switch to the image 3 /// </summary> 4 /// <param name = "sender"> </param> 5 // <param name = "e"> </param> 6 private void picturebox#click (object sender, eventArgs e) 7 {8 Random r = new Random (); 9 string str = string. empty; 10 // generates a random number of 5 digits, such as 9053111 for (int I = 0; I <5; I ++) 12 {13 str + = r. next (0, 10); 14} 15 Bitmap bitmap = new Bitmap (150, 40); 16 Graphics g = Graphics. fromImage (bitmap); 17 // predefined font styles and colors 18 string [] fonts = {"", "", ""}; 19 Color [] colors = {Color. yellow, Color. blue, Color. black, Color. red, Color. orange}; 20 // because the font and color of each digit may be different, 21 // the random number generated in a loop is drawn to the image 22 for (int I = 0; I <str. length; I ++) 23 {24 Point p = new Point (I * 30, 0); 25g. drawString (str [I]. toString (), new Font (fonts [r. next (0, 5)], 20, FontStyle. bold), new SolidBrush (colors [r. next (0, 5)]), p); 26} 27 // draw 50 lines within the image range in a loop 28 for (int I = 0; I <50; I ++) 29 {30 // the starting Point of the guaranteed line is within the image range 31 Point p1 = new Point (r. next (0, bitmap. width), r. next (0, bitmap. height); 32 Point p2 = new Point (r. next (0, bitmap. width), r. next (0, bitmap. height); 33g. drawLine (new Pen (Brushes. green), p1, p2); 34} 35 // Add some pixels 36 for (int I = 0; I <300; I ++) 37 {38 Point p1 = new Point (r. next (0, bitmap. width), r. next (0, bitmap. height); 39 bitmap. setPixel (p1.X, p1.Y, Color. green); 40} 41 // 42 pictureBox1.Image = bitmap; 43} is displayed in PictureBox in winForm}View Code
The final result is as follows: