public CommonResult<String> getCode(HttpServletRequest request, HttpServletResponse response){
//生成图片宽度
int width = 130;
int height = 45;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.setColor(Color.white);//验证码背景色
g.fillRect(0,0,width,height);
Random random = new Random();
String checkCode = getCheckCode();
//把验证码放到session中
request.getSession().setAttribute("checkCode_session",checkCode);
Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
g.setColor(color);
g.setFont(new Font("微软雅黑",Font.BOLD,40));
//向图片写入验证码
g.drawString(checkCode,15,33);
//画干扰线
for(int i = 0;i < 6;i++){
Color line = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
g.setColor(line);
g.drawLine(random.nextInt(width), random.nextInt(height),random.nextInt(width), random.nextInt(height));
}
//添加图块噪点
for(int i = 0;i < 30;i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
Color rect = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
g.setColor(rect);
g.fillRect(x,y,2,2);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
ImageIO.write(image,"png",stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
String codeImg = Base64Utils.encodeToString(stream.toByteArray());
return CommonResult.success(codeImg);
}
/**
* 生成四位验证码
* @return
*/
public String getCheckCode(){
//可生成的字符集
String base = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int size = base.length();
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0;i < 4;i++){
//产生随机数
int index = random.nextInt(size);
char c = base.charAt(index);
sb.append(c);
}
return sb.toString();
}
前端使用
<img src="data:image/png;base64,${base64资源}">