ImageCodeUtil.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.welampiot.utils;
  2. import com.welampiot.security.ImageCode;
  3. import java.awt.*;
  4. import java.awt.image.BufferedImage;
  5. import java.util.Random;
  6. public class ImageCodeUtil {
  7. /**
  8. * 创建图片验证码
  9. * @return
  10. */
  11. public static ImageCode createImageCode() {
  12. int width = 100; // 验证码图片宽度
  13. int height = 36; // 验证码图片长度
  14. int length = 4; // 验证码位数
  15. int expireIn = 120; // 验证码有效时间 120s
  16. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  17. Graphics g = image.getGraphics();
  18. Random random = new Random();
  19. g.setColor(getRandColor(200,250));
  20. g.fillRect(0,0,width,height);
  21. g.setFont(new Font("Times New Roman",Font.ITALIC, 35));
  22. g.setColor(getRandColor(160,200));
  23. for(int i = 0; i< 155; i++){
  24. int x = random.nextInt(width);
  25. int y = random.nextInt(height);
  26. int xl = random.nextInt(12);
  27. int yl = random.nextInt(12);
  28. g.drawLine(x, y, x + xl, y + yl);
  29. }
  30. StringBuilder sRand = new StringBuilder();
  31. String rand = null;
  32. for(int i = 0; i<length; i++){
  33. int anInt = random.nextInt(57);
  34. if(anInt >= 10) {
  35. if(anInt + 65 >=91 && anInt + 65 <= 96) {
  36. anInt += 6;
  37. }
  38. char ch = (char) (anInt + 65);
  39. rand = String.valueOf(ch);
  40. } else {
  41. rand = String.valueOf(anInt);
  42. }
  43. sRand.append(rand);
  44. g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  45. g.drawString(rand, 15 * i + 15, 28);
  46. }
  47. g.dispose();
  48. return new ImageCode(image, sRand.toString(),expireIn);
  49. }
  50. private static Color getRandColor(int fc, int bc) {
  51. Random random = new Random();
  52. if(fc > 255) {
  53. fc = 255;
  54. }
  55. if (bc > 255) {
  56. bc = 255;
  57. }
  58. int r = fc + random.nextInt(bc - fc);
  59. int g = fc + random.nextInt(bc - fc);
  60. int b = fc + random.nextInt(bc - fc);
  61. return new Color(r, g, b);
  62. }
  63. }