CaptchaUtil.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.ctsi.utils;
  2. import javax.imageio.ImageIO;
  3. import javax.servlet.http.HttpSession;
  4. import java.awt.*;
  5. import java.awt.image.BufferedImage;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.util.Random;
  9. public class CaptchaUtil {
  10. private static final int WIDTH = 140;
  11. private static final int HEIGHT = 35;
  12. private static final int LENGTH = 4;
  13. public static byte[] generateCaptcha(HttpSession session) throws IOException {
  14. BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
  15. Graphics g = image.getGraphics();
  16. g.setColor(Color.WHITE);
  17. g.fillRect(0, 0, WIDTH, HEIGHT);
  18. g.setColor(Color.BLACK);
  19. g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
  20. String captcha = generateRandomString();
  21. g.setFont(new Font("Arial", Font.PLAIN, 20));
  22. for (int i = 0; i < LENGTH; i++) {
  23. g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
  24. g.drawString(String.valueOf(captcha.charAt(i)), 20 * i + 10, 30);
  25. }
  26. for (int i = 0; i < 5; i++) {
  27. g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
  28. int x1 = new Random().nextInt(WIDTH);
  29. int y1 = new Random().nextInt(HEIGHT);
  30. int x2 = new Random().nextInt(WIDTH);
  31. int y2 = new Random().nextInt(HEIGHT);
  32. g.drawLine(x1, y1, x2, y2);
  33. }
  34. g.dispose();
  35. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  36. ImageIO.write(image, "png", outputStream);
  37. session.setAttribute("captcha", captcha);
  38. return outputStream.toByteArray();
  39. }
  40. private static String generateRandomString() {
  41. String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  42. StringBuilder stringBuilder = new StringBuilder();
  43. Random random = new Random();
  44. for (int i = 0; i < LENGTH; i++) {
  45. int index = random.nextInt(characters.length());
  46. stringBuilder.append(characters.charAt(index));
  47. }
  48. return stringBuilder.toString();
  49. }
  50. }