生成动态验证码图片之小小工具

小工具生成如下验证码图片~~~

1. 工具类

/**
 * 生成动态验证码
 * 
 * @author hui.zhang
 * 
 */
public class VerifyCode {
    public static final int WIDTH = 125;
    public static final int HEIGHT = 35;
    private static StringBuilder sb;

    /**
     * 保存图片到指定的输出流
     * @param image
     * @param out
     * @throws IOException
     */
    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "jpg", out);
    }
    
    public BufferedImage getImage() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D bi = (Graphics2D) image.getGraphics();
        // 设置背景色
        setBackGround(bi);
        // 设置边框
        setBorder(bi);
        // 画干扰线
        drawRandLine(bi);
        // 写随机数
        getCode(bi);
        
        return image;
    }

    private static void setBackGround(Graphics bi) {
        bi.setColor(Color.WHITE);
        bi.fillRect(0, 0, WIDTH, HEIGHT);
    }

    private static void setBorder(Graphics bi) {
        bi.setColor(Color.BLUE);
        bi.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
    }

    private static void drawRandLine(Graphics bi) {
        bi.setColor(Color.GREEN);
        for (int i = 0; i < 5; i++) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);

            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            bi.drawLine(x1, y1, x2, y2);
        }

    }

    

    private static void getCode(Graphics2D bi) {
        bi.setColor(Color.RED);
        bi.setFont(new Font("宋体", Font.BOLD, 32));
        String base = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int x = 10;
        sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int degree = new Random().nextInt() % 30;
            String ch = base.charAt(new Random().nextInt(base.length())) + "";
            bi.rotate(degree * Math.PI / 180, x, 25);
            bi.drawString(ch, x, 25);
            sb.append(ch);
            bi.rotate(-degree * Math.PI / 180, x, 25);
            x += 30;
        }
    }

    /**
     * 返回图片中验证码的文本 全为小写字母为了方便验证
     * 
     * @return
     */
    public String getText() {
        return sb.toString().toLowerCase();
    }

}

2. 测试类

VerifyCode.output(new FileOutputStream(new File("G:\a.jpg")));
String text = VerifyCode.getText();
System.out.println(text);

3. 打印结果

p75n

原文地址:https://www.cnblogs.com/stefan95/p/7587572.html