Java 生成图片验证码
// 图片高度
private static final int IMG_HEIGHT = 40;
// 图片宽度
private static final int IMG_WIDTH = 100;
// 验证码X坐标
private static final int CODE_X = 25;
// 验证码Y坐标
private static final int CODE_Y = 20;
public void getVerificationCode(String code) {
Random random = new Random();
//构造BufferedImage图像对象
BufferedImage bufferedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
BufferedImage.TYPE_INT_RGB);
//获取绘图对象
Graphics graphics = bufferedImage.getGraphics();
for (int i = 0; i < code.length(); i++) {
//设置字体颜色
graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
//绘制字体
graphics.drawString((code.charAt(i) + "").toUpperCase(Locale.ROOT),
(i * CODE_X) + random.nextInt(9), CODE_Y + random.nextInt(9));
}
try {
//写入图片
ImageIO.write(bufferedImage, "JPG", new FileOutputStream("F:/code.jpg"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestUtils testUtils = new TestUtils();
testUtils.getVerificationCode("aB12");
}
结果图片
还没有评论,来说两句吧...