The article is from my blog

The text before

I have done a Web project login interface, which has a verification code module, involving JavaIO and Java AWT tools, so I plan to write an introduction, incidentally to the source code of the project to do a little change

The body of the

1. The variable

Start by defining a few variables you need

private int width=50; Private int height=15; Private Random =new Random(); Private Color Color =new Color(255,255,255); // White background private String text; // Text on the imageCopy the code
2. Random characters and colors

Random characters contain 10 digits and 26 letters

// Generate random character private charrandomChar() {// Select a random number and generate String numbers ="1234567890qwertyuiopasdfghjklzxcvbnm"; int index=random.nextInt(numbers.length()); // Convert to charreturnnumbers.charAt(index); } // Generate a random Color private ColorrandomColorInt red=random. NextInt (255); int green=random.nextInt(255); int blue=random.nextInt(255); // Returns a randomly generated colorreturn new Color(red,green,blue);
    }
Copy the code
3. Line interference
Private void drawLine(Graphics g){for(int i = 0; i < 2; I++) {// set the line color g.setcolor (randomColor()); // The length of the line is from (x1,y1) to (x2,y2) g.drawline (random.nextint (width), random.nextint (height), random.nextint (width), random.nextInt(height)); }}Copy the code
4. Text in the verification code
// Returns the text in the captcha image public StringgetText()
    {
        return text;
    }
Copy the code
5. Image buffer
// Create image buffer private BufferedImagecreateImage() {/ / parameter for the width, height and image type BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); Graphics g=image.getGraphics(); // set the color g.setcolor (color); // fill the content g.fillrect (0,0,width,height);return image;
    }
Copy the code
// Get image buffer public BufferedImagegetImage() { BufferedImage image = createImage(); // create buffer Graphics g = image.getgraphics (); StringBuilder StringBuilder = new StringBuilder(); // Verification code text // The verification code contains 4 charactersfor(int i=0; i<4; i++) { String str = String.valueOf(randomChar()); // Generate random characters, convert char to String stringBuilder.append(STR); // Add the generated random character to stringBuilder g.setColor(randomColor()); STR, I * width / 4, height); } drawLine(g); // Add interference line text = stringBuilder.toString(); // Assign the generated string to the text for validationreturn image;
    }
Copy the code
6. Output images
Public static void Output (BufferedImage image, OutputStream out) throws IOException {// OutputStream out as a JPEG imageio. write(image,"JPG",out);
    }
Copy the code
Demo

Output images directly to my desktop

The result after running:

And with that, the simple captcha is done