@RequestMapping(“/identifyCode”)
public void identifyCode(HttpServletResponse response,HttpSession httpSession){
BufferedImage bufferedImage = new BufferedImage(150,40,BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.createGraphics();
graphics.setColor(Color.red);
graphics.setFont(new Font(“黑体”,Font.BOLD,32));
String code =getCode().toString();
httpSession.setAttribute(“code”,code);
graphics.drawString(code,10,25);
try {
ImageIO.write(bufferedImage,”png”,response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public StringBuffer getCode(){
Random random = new Random();
StringBuffer code = new StringBuffer();
String[] allStr = new String[]{"1","2","3","4","5","6","7","8","8","a","b","c","d","e","f","g","h","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
for(int i = 0; i < 6; i++){
code.append(allStr[random.nextInt(allStr.length)]);
}
return code;
}

本文介绍了一种使用Java生成包含随机字符的验证码图片的方法。通过设置图片尺寸、字体样式及颜色等属性,实现了验证码的生成,并将其以PNG格式输出到HTTP响应中。
1855

被折叠的 条评论
为什么被折叠?



