public class VerifyCode {
/*在下面字符内生成校验码*/
private String VERIFY_CODES = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
public String generateVerifyCode(HttpServletResponse response) throws IOException {
int IMG_WIDTH = 72;
int IMG_HEIGHT = 30;
Random random = new Random();
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,IMG_WIDTH,IMG_HEIGHT);
g.setFont(new Font("楷体",Font.BOLD,25));
/* #1 提供变量保存随机字符数据 */
StringBuilder sb = new StringBuilder();
for(int i = 1 ; i <= 4 ; i ++){
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int len = random.nextInt(VERIFY_CODES.length());
String str = VERIFY_CODES.substring(len,len+1);
/* #2 存放随机字符串 */
sb.append( str );
g.drawString(str, IMG_WIDTH / 6 * i , 22 );
}
/* #3 获得随机字符串 */
String randomStr = sb.toString();
// 生成随机干扰线
for (int i = 0; i < 30; i++) {
//随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int x = random.nextInt(IMG_WIDTH - 1);
int y = random.nextInt(IMG_HEIGHT - 1);
int x1 = random.nextInt(12) + 1;
int y1 = random.nextInt(6) + 1;
g.drawLine(x, y, x - x1, y - y1);
}
/*通过response接口返回图片内容*/
ImageIO.write(image,"jpeg", response.getOutputStream());
return randomStr;
}
}
springboot生成图片验证码方法
最新推荐文章于 2025-05-15 20:49:36 发布