用Java实现生成图片验证码

通过代码实现生成一个随机验证码图片,且生成后自动打开:

package day_12_17;

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

/**
 * @author soberw
 * @Classname Fonts
 * @Description 验证码生成
 * @Date 2021-12-17 15:14
 */
public class Fonts {
    public static void main(String[] args) {
        Font font = new Font("宋体", Font.BOLD, 50);

        BufferedImage bi = new BufferedImage(160, 100, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = bi.createGraphics();
        //这三行是设置抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);

        Random random = new Random();
        String letter = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        g2.setColor(Color.BLACK);
        g2.drawLine(0,0,160,100);
        int add = 0;
        double ro = 0.2;
        for (int i = 0; i < 4; i++) {
            font.deriveFont(Font.BOLD, 30f);
            int r = random.nextInt(256);
            int g = random.nextInt(256);
            int b = random.nextInt(256);
            int a = random.nextInt(100) + 150;
            g2.setColor(new Color(r, g, b, a));
            g2.setFont(font);
            String let = String.valueOf(letter.charAt(random.nextInt(letter.length())));
            if(random.nextBoolean()){
                ro = -ro;
            }
            g2.rotate(ro);
            g2.drawString(let, random.nextInt(10) + add, 60);
            add += 40;
            g2.rotate(-ro);

        }
        g2.dispose();

        try {
            ImageIO.write(bi, "png", new File("E:\\HelloJava\\soberw\\src\\main\\java\\ver.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Runtime.getRuntime().exec("cmd /k start E:\\HelloJava\\soberw\\src\\main\\java\\ver.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:
请添加图片描述

posted @ 2022-02-09 19:45  soberw-  阅读(78)  评论(0编辑  收藏  举报