Learning notes: using GDI + to generate a simple verification code image, learning notes gdi

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.