Java生成简单的验证码图片

几个简单使用到的类

BufferedImage : 图像
Graphics2D :图像的上下文
Color : 颜色对象
Font : 字体对象
具体信息大家可以查一下JDK文档。我用的是这个 这个

具体实现

VerifyCode.class

包含了验证码图片的基本信息,包括但不局限于图片的尺寸、背景颜色、干扰线的数目,干扰线的颜色、验证码的格式、验证码的颜色等等。

import java.awt.*;
import java.util.Random;

/**
 * @author 三文鱼
 * @title 验证码实体类
 * @description 包含验证码的必要信息
 * @date 2022/4/26
 **/
public class VerifyCode {
    //图片的宽、高
    private int width;
    private int height;

    //干扰线的条数
    private int lineCount;
    //干扰线的颜色
    private Color lineColor;
    //干扰线的长度
    private int lineLength;

    //验证码背景颜色
    private Color bgColor;

    //验证码颜色
    private Color codeColor;
    //验证码类型 字符、数字、或者字符数字的随机组合
    private int codeType;

    //旋转角度
    private int angle;
    //字体
    private Font font;

    //用于产生随机颜色和数字
    private static Random random;

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getLineCount() {
        return lineCount;
    }

    public void setLineCount(int lineCount) {
        this.lineCount = lineCount;
    }

    public Color getBgColor() {
        return bgColor;
    }

    public void setBgColor(Color bgColor) {
        this.bgColor = bgColor;
    }

    public Color getCodeColor() {
        return codeColor;
    }

    public void setCodeColor(Color codeColor) {
        this.codeColor = codeColor;
    }

    public int getCodeType() {
        return codeType;
    }

    public void setCodeType(int codeType) {
        this.codeType = codeType;
    }

    public int getAngle() {
        return angle;
    }

    public void setAngle(int angle) {
        this.angle = angle;
    }

    public Font getFont() {
        return font;
    }

    public void setFont(Font font) {
        this.font = font;
    }

    public static Random getRandom() {
        return random;
    }

    public static void setRandom(Random random) {
        VerifyCode.random = random;
    }

    public Color getLineColor() {
        return lineColor;
    }

    public void setLineColor(Color lineColor) {
        this.lineColor = lineColor;
    }

    public int getLineLength() {
        return lineLength;
    }

    public void setLineLength(int lineLength) {
        this.lineLength = lineLength;
    }

    static {
        random = new Random();
    }


    public VerifyCode() {
    }

    //不产生干扰线
    public VerifyCode(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public VerifyCode(int width, int height, int lineCount) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
    }

    public VerifyCode(int width, int height, int lineCount , int codeType) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.codeType = codeType;
    }

    public VerifyCode(int width, int height, int lineCount , int codeType , int angle) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.codeType = codeType;
        this.angle = angle;
    }

    public VerifyCode(int width, int height, int lineCount, int codeType, int angle, Font font) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.codeType = codeType;
        this.angle = angle;
        this.font = font;
    }

    public VerifyCode(int width, int height, int lineCount, Color bgColor) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.bgColor = bgColor;
    }

    public VerifyCode(int width, int height, int lineCount, Color bgColor, Color codeColor) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.bgColor = bgColor;
        this.codeColor = codeColor;
    }

    public VerifyCode(int width, int height, int lineCount, Color bgColor, Color codeColor, int codeType) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.bgColor = bgColor;
        this.codeColor = codeColor;
        this.codeType = codeType;
    }

    public VerifyCode(int width, int height, int lineCount, Color bgColor, Color codeColor, int codeType, int angle) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.bgColor = bgColor;
        this.codeColor = codeColor;
        this.codeType = codeType;
        this.angle = angle;
    }

    public VerifyCode(int width, int height, int lineCount, Color bgColor, Color codeColor, int codeType, int angle, Font font) {
        this.width = width;
        this.height = height;
        this.lineCount = lineCount;
        this.bgColor = bgColor;
        this.codeColor = codeColor;
        this.codeType = codeType;
        this.angle = angle;
        this.font = font;
    }
}

VerifyCodeUtil.class

该类是验证码图片的工具类,用于生成验证码图片,也可以将生成的验证码图片以输出流的方式输出到文件或者相应的response中。

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

/**
 * @author 三文鱼
 * @title 验证码工具类
 * @description
 * @date 2022/4/26
 **/
public class VerifyCodeUtil {
    private static final String TARGAET_STRING = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioplkjhgfdsazxcvbnm0123456789";
   
    
    /*
     * @description 获得验证码图片对象
     * @author 三文鱼
     * @date 16:07 2022/4/26 
     * @param verifyCode
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage getVerifyCodeImage(VerifyCode verifyCode) {
        if (verifyCode == null)
            return null;

        if(verifyCode.getWidth() <=105 || verifyCode.getHeight() <= 35) {
            verifyCode.setWidth(105);
            verifyCode.setHeight(35);
        }

        int width = verifyCode.getWidth();
        int height = verifyCode.getHeight();
        //以三原色为底色构建图像
        final BufferedImage bufferedImage = new BufferedImage(width , height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
        //随机数种子
        final Random random = VerifyCode.getRandom();
        //设置默认底色和边框
        if(verifyCode.getBgColor() != null) {
            graphics2D.setColor(verifyCode.getBgColor());
        }else {
            graphics2D.setColor(Color.WHITE);
        }
        //填充颜色
        graphics2D.fillRect(0 , 0 , verifyCode.getWidth() , verifyCode.getHeight());
        //绘出边框
        graphics2D.drawRect(0 , 0 , verifyCode.getWidth()-1 , verifyCode.getHeight() - 1);

        //生成干扰线
        int count = verifyCode.getLineCount();
        //干扰线颜色
        Color lineColor = verifyCode.getLineColor();
        //干扰线的长度
        int lineLength = verifyCode.getLineLength();
        if (lineLength == 0)
            lineLength = 1;

        if(count == 0) {
            count = 20;
        }
        for (int i =0; i <count; i++) {
            if(lineColor != null) {
                graphics2D.setColor(lineColor);
            }else {
                graphics2D.setColor(getRandomColor(random));
            }
            //生成随机的起点坐标
            int x = random.nextInt(width - 1 - 1);
            int y = random.nextInt(height - 1 -1);
            //生成随机的终点坐标
            int xEnd = x + random.nextInt(lineLength);
            int yEnd = y + random.nextInt(lineLength);
            //绘制线条到图像里面
            graphics2D.drawLine(x, y , xEnd, yEnd);
        }

        //获取验证码用于生成图片
        final String code = getRandomCode(random , 0);
        //验证码颜色、字体、旋转角度
        Color fontColor = verifyCode.getCodeColor();
        Font font = verifyCode.getFont();
        int angle = verifyCode.getAngle();
        int rotateAngle = 0;
        for(int i =0; i < code.length(); i++) {
            //设置字体颜色
            if(fontColor == null) {
                graphics2D.setColor(getRandomColor(random));
            }else {
                graphics2D.setColor(fontColor);
            }
            //设置字体样式
            if (font == null) {
                graphics2D.setFont(getRandomFont(random , height));
            }else{
                graphics2D.setFont(font);
            }

            int x = (width/5)*i + width/5;

            if(angle != 0) {
                //旋转图像
                rotateAngle = random.nextInt(angle) - angle/2;
                graphics2D.rotate(Math.toRadians(rotateAngle) ,x  , height/2);
            }
            //绘制字符
            graphics2D.drawString(String.valueOf(code.charAt(i)) , x , height/2);
            if(angle != 0) {
                //逆向旋转 将图像转正
                graphics2D.rotate(-Math.toRadians(rotateAngle) ,x  , height/2);
            }
        }
        graphics2D.dispose();// 图象生效  释放资源

        return bufferedImage;
    }


    /*
     * @description  获取随机的颜色对象
     * @author 三文鱼
     * @date 16:07 2022/4/26
     * @param random
     * @return java.awt.Color
     **/
    public static Color getRandomColor(Random random) {
        return new Color(random.nextInt(255) , random.nextInt(255), random.nextInt(255));
    }

    /*
     * @description 产生随机字符串
     * @author 三文鱼
     * @date 16:06 2022/4/26 
     * @param random
     * @param type  0-字母  1-数字 2-数字+字母
     * @return java.lang.String
     **/
    public static String getRandomCode(Random random , int type) {
        StringBuilder stringBuilder = new StringBuilder();
        int base = 0;
        int length = 51;
        //截取数字
        if(type == 1) {
            length = 9;
            base = 52;
        }
        //数字 字符串结合
        if(type == 2) {
            length = 61;
        }
        for(int i =0; i < 4; i++) {
            stringBuilder.append(TARGAET_STRING .charAt(random.nextInt(length) + base));
        }
        return stringBuilder.toString();
    }

    /*
     * @description 设置随机字体大小
     * @author 三文鱼
     * @date 16:05 2022/4/26 
     * @param random
     * @param height
     * @return java.awt.Font
     **/
    public static Font getRandomFont(Random random , int height) {
        return new Font("楷体" , Font.BOLD , random.nextInt(20) + height/3);
    }

    /*
     * @description 将图片以流的形式输出  可以是本地的文件或者是response的输出流
     * @author 三文鱼
     * @date 16:05 2022/4/26
     * @param image
     * @param out
     * @return void
     **/
    public static void storeImagetoF(BufferedImage image , OutputStream out)  throws IOException {
        ImageIO.write(image ,"JPEG", out);
    }
}

UtilTest.class

简单测试类

import java.awt.*;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 三文鱼
 * @title
 * @description
 * @date 2022/4/26
 **/
public class UtilTest {
    public static void main(String[] args) {
        //默认参数生成的验证码图片
        //VerifyCode verifyCode = new VerifyCode();
        //自定义参数生成的验证码图片
        VerifyCode verifyCode = new VerifyCode(300 , 100 , 200 , Color.WHITE , Color.BLACK, 2 , 45);
        for (int i = 0; i < 5; i++) {
            try{
                Thread.sleep(1000);
                //文件名称
                String imageName = getNowDate();
                //输出的完整路径
                String totalPath = "F:\\学习记录\\image\\" + imageName +".jpg";
                VerifyCodeUtil.storeImagetoF(VerifyCodeUtil.getVerifyCodeImage(verifyCode) , new FileOutputStream(totalPath));
            }catch (Exception exception){
                exception.printStackTrace();
            }
        }
    }

    /*
     * @description 获取当前的时间作为图片文件名称
     * @author 三文鱼
     * @date 16:17 2022/4/26
     * @return java.lang.String
     **/
    public static String getNowDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
}

测试结果

默认生成的验证码文件,由于默认是宽是一百,高是三十,所以放大后会模糊。
在这里插入图片描述
自定义数据生成为验证码图片
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成图片验证码可以使用 Java 的 BufferedImage 类和 Graphics 类,以下是一个简单的示例代码: ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; public class ImageCode { private int width = 100; // 验证码图片的宽度 private int height = 40; // 验证码图片的高度 private int codeCount = 4; // 验证码字符个数 private int lineCount = 20; // 干扰线数量 private String code = null; // 验证码 private BufferedImage buffImg = null; // 验证码图片 private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'}; public ImageCode() { createImageCode(); } public void createImageCode() { int x = 0, fontHeight = 0, codeY = 0; int red = 0, green = 0, blue = 0; x = width / (codeCount + 2); fontHeight = height - 5; codeY = height - 8; buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.createGraphics(); Random random = new Random(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width / 8); int ye = ys + random.nextInt(height / 8); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawLine(xs, ys, xe, ye); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < codeCount; i++) { String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawString(strRand, (i + 1) * x, codeY); randomCode.append(strRand); } code = randomCode.toString(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code; } } ``` 使用时可以直接调用 `ImageCode` 类的 `getBuffImg` 方法获取生成验证码图片,调用 `getCode` 方法获取验证码字符串。例如: ```java ImageCode imageCode = new ImageCode(); BufferedImage buffImg = imageCode.getBuffImg(); String code = imageCode.getCode(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值