基本参数
private static final String RANGE_RANDOM_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int WIDTH = 100;
private static final int HEIGHT = 32;
private static final int LINE_NUM = 40;
private static final int STE_NUM = 4;
private static final Font DEFAULT_FONT = new Font("Times New Roman", Font.ROMAN_BASELINE, 22);
private static final Random RANDOM = new Random();
获取随机字符串
public static String getRandomString() {
StringBuffer rssb = new StringBuffer();
for(int index = 0; index < STE_NUM; index++) {
rssb.append(RANGE_RANDOM_STR.charAt(RANDOM.nextInt(RANGE_RANDOM_STR.length())));
}
return rssb.toString();
}
获得随机颜色
private static Color getRandColor(int fc, int bc) {
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + RANDOM.nextInt(bc - fc - 16);
int g = fc + RANDOM.nextInt(bc - fc - 14);
int b = fc + RANDOM.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
绘制干扰线
private static void drowLine(Graphics graphics) {
int x = RANDOM.nextInt(WIDTH);
int y = RANDOM.nextInt(HEIGHT);
int xl = RANDOM.nextInt(13);
int yl = RANDOM.nextInt(15);
graphics.drawLine(x, y, x + xl, y + yl);
}
绘制字符串
private static void drowString(Graphics graphics, String randomString) {
graphics.setFont(DEFAULT_FONT);
graphics.setColor(new Color(RANDOM.nextInt(101), RANDOM.nextInt(111), RANDOM.nextInt(121)));
graphics.translate(RANDOM.nextInt(3), RANDOM.nextInt(3));
graphics.drawString(randomString, 20, 20);
}
获取图片
public static BufferedImage getImage(String randomString) {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.getGraphics();
graphics.fillRect(0, 0, WIDTH, HEIGHT);
graphics.setFont(DEFAULT_FONT);
graphics.setColor(getRandColor(110, 133));
for (int i = 0; i <= LINE_NUM; i++) {
drowLine(graphics);
}
drowString(graphics, randomString);
graphics.dispose();
return image;
}
public static BufferedImage getImage() {
return getImage(getRandomString());
}
HTTP响应设置
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
try {
String randomString = VerifyUtils.getRandomString();
BufferedImage image = VerifyUtils.getImage(randomString);
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
LOGGER.error("IOException : {}", e.getMessage(), e);
}