Browse Source

图片验证码图形修改

wangmh 7 years ago
parent
commit
d0e026652a
1 changed files with 27 additions and 1 deletions
  1. 27 1
      sso-server/src/main/java/com/uas/sso/util/CaptchaUtil.java

+ 27 - 1
sso-server/src/main/java/com/uas/sso/util/CaptchaUtil.java

@@ -8,6 +8,7 @@ import java.awt.Font;
 import java.awt.Graphics2D;
 import java.awt.image.BufferedImage;
 import java.io.IOException;
+import java.util.Date;
 import java.util.Random;
 import javax.imageio.ImageIO;
 import javax.servlet.ServletOutputStream;
@@ -84,6 +85,7 @@ public class CaptchaUtil {
 
         int width = 100;
         int height = 30;
+        int lines = 10;
 
         Color color = getRandomColor();
         Color reverse = getReverseColor(color);
@@ -95,7 +97,31 @@ public class CaptchaUtil {
         g.setColor(color);
         g.fillRect(0, 0, width, height);
         g.setColor(reverse);
-        g.drawString(randomString, 18, 20);
+        Random r = new Random(new Date().getTime());
+
+        // 生成验证码
+        for (int i = 0; i < 4; i++) {
+            int a = r.nextInt(10);
+            int y = 10 + r.nextInt(20);// 10~30范围内的一个整数,作为y坐标
+//            g.rotate(30 * Math.PI / 180);
+            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
+            g.setColor(c);
+            g.drawString("" + CHARS[random.nextInt(CHARS.length)], 5 + i * width / 4, y);
+        }
+
+        /**
+         * 加圆点
+         */
+        for (int i = 0, n = random.nextInt(100); i < n; i++) {
+            g.drawOval(random.nextInt(width), random.nextInt(height), 1, 1);
+        }
+
+        // 干扰线
+        for (int i = 0; i < lines; i++) {
+            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
+            g.setColor(c);
+            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
+        }
 
         // 转成JPEG格式
         ServletOutputStream out = response.getOutputStream();