java imageio_Java使用imageio、awt生成图片验证码

该博客介绍了一个Java实现的验证码生成工具类,包括创建内存图像对象、设置背景颜色、绘制随机字符串、添加干扰线等步骤。同时,代码将生成的验证码存储到Redis中,设置1分钟的有效期,以便于后续的登录校验。
摘要由CSDN通过智能技术生成

public classCheckCodeTool {private Integer width = 80;private Integer height = 38;publicString getCheckCode(BaseForm baseForm) {/** 绘图*/

//step1,创建一个内存映像对象(画板)

BufferedImage image = newBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//step2,获得画笔

Graphics g =image.getGraphics();//step3,给笔上色//Random r = new Random();

SecureRandom r = newSecureRandom();//g.setColor(new Color(r.nextInt(255), r.nextInt(255),r.nextInt(255)));//step4,给画板设置背景颜色

g.fillRect(0, 0, width, height);//step5,绘制一个随机的字符串

String number =getNumber();

g.setColor(new Color(0, 0, 0));//存储到redis(用于登录校验)

if (baseForm != null &&StringUtils.isNotEmpty(baseForm.getSessionId())) {

String redisCheckCodeId= "CheckCodeId";try{if(RedisUtil.getInstance().isExists(redisCheckCodeId)) {

RedisUtil.getInstance().remove(redisCheckCodeId);

}

RedisUtil.getInstance().setStringWithSeconds(redisCheckCodeId,number,60);//1分钟时效

} catch(Exception e) {

System.out.println("getCheckCode:error:" +e.toString());

}

}//new Font(字体,风格,大小)

g.setFont(new Font(null, Font.ITALIC, 20));

g.drawString(number,5, 25);//step6,加一些干扰线

for (int i = 0; i < 8; i++) {

g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));

g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));

}/** 压缩图片并输出到客户端(浏览器)*/ByteArrayOutputStream out= newByteArrayOutputStream();

String base64String= "";try{

ImageIO.write(image,"jpeg", out);

base64String=Base64Utils.encode(out.toByteArray());

}catch(Exception e) {

e.printStackTrace();

}finally{if (out != null) {try{

out.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}returnbase64String;

}//生成随机数作为验证码

privateString getNumber() {

String number= "";

String pool= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

SecureRandom r= newSecureRandom();for (int i = 0; i < 4; i++) {

number+=pool.charAt(r.nextInt(pool.length()));

}returnnumber;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值