美文网首页
Java 图形验证码

Java 图形验证码

作者: ZM_微笑向阳 | 来源:发表于2021-11-01 11:24 被阅读0次

    源码

    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Random;
    
    /**
     * @author Yawei Xi
     * @date 2018-10-24
     */
    public class ImageCaptcha {
    /**
     * 随机数
     */
    private static final Random RANDOM = new Random();
    /**
     * 字体
     */
    private static final String[] FONT_NAMES = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
    /**
     * 字母库
     */
    private static final String CODE = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    /**
     * 字符串的长度
     */
    private int length;
    /**
     * 验证码图片的高度
     */
    private int height;
    /**
     * 验证码图片的宽度
     */
    private int width;
    /**
     * 默认背景颜色
     */
    private Color bgColor;
    
    public ImageCaptcha() {
        this.bgColor = new Color(255, 255, 255);
        this.length = 4;
        this.height = 35;
        this.width = 70;
    }
    
    public ImageCaptcha(int length) {
        this.bgColor = new Color(255, 255, 255);
        this.length = length;
        this.height = 35;
        this.width = 70;
    }
    
    public ImageCaptcha(int length, int width, int height) {
        this.bgColor = new Color(255, 255, 255);
        this.length = length;
        this.height = height;
        this.width = width;
    }
    
    /**
     * 获取指定长度的随机字符串
     *
     * @return 随机字符串
     */
    private String getRandomString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(CODE.charAt(RANDOM.nextInt(CODE.length())));
        }
        return sb.toString();
    }
    
    /**
     * 将验证码图片保存为图片
     *
     * @param filePath 需要保存的文件路径
     */
    public void output(String filePath) {
        try {
            OutputStream os = new FileOutputStream(filePath);
            ImageIO.write(getCaptcha(), "JPEG", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 随机生成文字的颜色
     *
     * @return 颜色对象
     */
    private Color randomColor() {
        int red = RANDOM.nextInt(150);
        int green = RANDOM.nextInt(150);
        int blue = RANDOM.nextInt(150);
        return new Color(red, green, blue);
    }
    
    /**
     * 随机选择字体
     *
     * @return 字体
     */
    private Font randomFont() {
        int index = RANDOM.nextInt(FONT_NAMES.length);
        String fontName = FONT_NAMES[index];
        int style = RANDOM.nextInt(3);
        int size = RANDOM.nextInt(5) + 24;
        return new Font(fontName, style, size);
    }
    
    /**
     * 给验证码画干扰的线条
     *
     * @param image 验证码图片
     * @param w     验证码图片的宽度
     * @param h     验证码图片的高度
     */
    private void drawLine(BufferedImage image, int w, int h) {
        int num = 3;// 画三条
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = RANDOM.nextInt(w);
            int y1 = RANDOM.nextInt(h);
            int x2 = RANDOM.nextInt(w);
            int y2 = RANDOM.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.BLUE);
            g2.drawLine(x1, y1, x2, y2);
        }
    }
    
    /**
     * 生成验证码的背景图片
     *
     * @param c 颜色
     * @param w 宽度
     * @param h 高度
     * @return 生成的图片
     */
    private BufferedImage createBGImage(Color c, int w, int h) {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(c);
        g2.fillRect(0, 0, w, h);
        return image;
    }
    
    /**
     * 将文字写入图片
     *
     * @param s 需要写进图片的字符串
     * @param c 图片背景颜色
     * @param w 宽度
     * @param h 高度
     * @return 验证码
     */
    private BufferedImage createCaptcha(String s, Color c, int w, int h) {
        BufferedImage image = createBGImage(c, w, h);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        // 向图片中画字符
        for (int i = 0; i < s.length(); i++) {
            float x = i * 1.0F * w / s.length();
            g2.setFont(randomFont());
            g2.setColor(randomColor());
            // 首字符的基线位于用户空间的 (x, h-5) 位置处 原点在左上角,X轴递增的方向是从左向右;Y轴是从上到下
            // 在提供的坐标位于基线上最左边字符的情况下,可以从右到左呈现字形 h-5表示y轴方向,向上偏移了5
            g2.drawString(String.valueOf(s.charAt(i)), x, h - 5);
        }
        drawLine(image, w, h);
        return image;
    }
    
    /**
     * 获取验证码图片
     *
     * @return 验证码图片对象
     */
    public BufferedImage getCaptcha() {
        return createCaptcha(getRandomString(), bgColor, width, height);
    }
    }
    

    测试用例

    /**
     * @author Yawei Xi
     * @date 2018-10-24
     */
    public class Test {
      public static void main(String[] args) throws Exception {
        String path = "D:\\test.jpg";
        ImageCaptcha ic = new ImageCaptcha();
        ic.output(path);
      }
    }
    

    相关文章

      网友评论

          本文标题:Java 图形验证码

          本文链接:https://www.haomeiwen.com/subject/ltszaltx.html