Captcha generation utility class

VerifyCode.java:

package com.blog.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class VerifyCode {
    private int w = 70;// Image width
    private int h = 35;// Image height
    private Random r = new Random();
    / / {" tahoma ", "Chinese regular script", "black", "HuaWenXin wei", "Chinese official script", "Microsoft jas black", "regular script _GB2312"}
    private String[] fontNames = { "宋体"."Chinese Script"."Black".Microsoft Yahei."Regular script _GB2312" };
    // Optional characters
    private String codes = "123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    / / the background color
    private Color bgColor = new Color(255.255.255);
    // The text on the verification code
    private String text;

    // Generate random colors
    private Color randomColor(a) {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }

    // Generate random fonts
    private Font randomFont(a) {
        int index = r.nextInt(fontNames.length);// Random font index
        String fontName = fontNames[index];// Generate random font names
        int style = r.nextInt(4);// Generate random styles, 0(no style), 1(bold), 2(italic), 3(bold + italic)
        int size = r.nextInt(5) + 24; // Generate random size from 24 to 28
        return new Font(fontName, style, size);
    }

    // Draw interference lines
    private void drawLine(BufferedImage image) {
        int num = 3;// Draw a total of 3 pieces
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {// Generate the coordinates of the two points, i.e., 4 values
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5 F));// Set the line width
            g2.setColor(Color.BLUE); // The interference line is blue
            g2.drawLine(x1, y1, x2, y2);Draw a line / /}}// Generate a random character
    private char randomChar(a) {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    / / create the BufferedImage
    private BufferedImage createImage(a) {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(this.bgColor);
        g2.fillRect(0.0, w, h);
        return image;
    }

    / /! Call this method to get the captcha
    public BufferedImage getImage(a) {
        BufferedImage image = createImage();// Create the image buffer
        Graphics2D g2 = (Graphics2D) image.getGraphics();// Get the drawing environment
        StringBuilder sb = new StringBuilder();// Used to load the generated captcha text
        // Draw 4 characters into the picture
        for (int i = 0; i < 4; i++) {// Loop four times to generate one character each time
            String s = randomChar() + "";// Generate a random letter
            sb.append(s); // Add letters to sb
            float x = i * 1.0 F * w / 4; // Sets the x coordinate of the current character
            g2.setFont(randomFont()); // Set a random font
            g2.setColor(randomColor()); // Set a random color
            g2.drawString(s, x, h - 5); / / drawing
        }
        this.text = sb.toString(); // Assigns the generated string to this.text
        drawLine(image); // Add interference lines
        return image;
    }

    // Returns the text on the captcha image
    public String getText(a) {
        return text;
    }

    // Save the image to the specified output stream
    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);// Output image stream, JPEG - The response content type must be set to image, otherwise the foreground will not recognize}}Copy the code

use

@GetMapping("getVerifyCode")
public void getVerifyCode(HttpServletResponse response) throws IOException {
    VerifyCode verifyCode = new VerifyCode();// Generate a captcha image
    OutputStream os = response.getOutputStream();// Get the file output stream
    VerifyCode.output(verifyCode.getImage(),os);
    os.flush();
    os.close();
}
Copy the code

Testing:

Reference documentation

Java generates verification code Image Background Java realizes verification code generation