1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
public class CaptchaUtil {
private static final String CODES = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int WIDTH = 120; private static final int HEIGHT = 40; private static final int CODE_LENGTH = 4; private static final Random RANDOM = new Random();
public static String generateCode() { StringBuilder code = new StringBuilder(); for (int i = 0; i < CODE_LENGTH; i++) { code.append(CODES.charAt(RANDOM.nextInt(CODES.length()))); } return code.toString(); }
public static String generateImageBase64(String code) throws IOException { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font("Arial", Font.BOLD, 32));
for (int i = 0; i < code.length(); i++) { g.setColor(new Color(RANDOM.nextInt(150), RANDOM.nextInt(150), RANDOM.nextInt(150))); int x = 20 + i * 25; int y = 28 + RANDOM.nextInt(8); g.drawString(String.valueOf(code.charAt(i)), x, y); }
for (int i = 0; i < 5; i++) { g.setColor(new Color(RANDOM.nextInt(200), RANDOM.nextInt(200), RANDOM.nextInt(200))); int x1 = RANDOM.nextInt(WIDTH); int y1 = RANDOM.nextInt(HEIGHT); int x2 = RANDOM.nextInt(WIDTH); int y2 = RANDOM.nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); }
for (int i = 0; i < 50; i++) { g.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255))); g.fillRect(RANDOM.nextInt(WIDTH), RANDOM.nextInt(HEIGHT), 1, 1); }
g.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "png", outputStream); String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray()); return "data:image/png;base64," + base64; } }
|