| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package com.ctsi.utils;
- import javax.imageio.ImageIO;
- import javax.servlet.http.HttpSession;
- import java.awt.*;
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.util.Random;
- public class CaptchaUtil {
- private static final int WIDTH = 140;
- private static final int HEIGHT = 35;
- private static final int LENGTH = 4;
- public static byte[] generateCaptcha(HttpSession session) throws IOException {
- BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
- Graphics g = image.getGraphics();
- g.setColor(Color.WHITE);
- g.fillRect(0, 0, WIDTH, HEIGHT);
- g.setColor(Color.BLACK);
- g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
- String captcha = generateRandomString();
- g.setFont(new Font("Arial", Font.PLAIN, 20));
- for (int i = 0; i < LENGTH; i++) {
- g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
- g.drawString(String.valueOf(captcha.charAt(i)), 20 * i + 10, 30);
- }
- for (int i = 0; i < 5; i++) {
- g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
- int x1 = new Random().nextInt(WIDTH);
- int y1 = new Random().nextInt(HEIGHT);
- int x2 = new Random().nextInt(WIDTH);
- int y2 = new Random().nextInt(HEIGHT);
- g.drawLine(x1, y1, x2, y2);
- }
- g.dispose();
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- ImageIO.write(image, "png", outputStream);
- session.setAttribute("captcha", captcha);
- return outputStream.toByteArray();
- }
- private static String generateRandomString() {
- String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- StringBuilder stringBuilder = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < LENGTH; i++) {
- int index = random.nextInt(characters.length());
- stringBuilder.append(characters.charAt(index));
- }
- return stringBuilder.toString();
- }
- }
|