|
@@ -0,0 +1,78 @@
|
|
|
+package org.bfkj.utils;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.*;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.ByteArrayOutputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.security.SecureRandom;
|
|
|
+import java.util.Base64;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+public class GenerateImage {
|
|
|
+ private static final int WIDTH = 120; // 图片宽度
|
|
|
+ private static final int HEIGHT = 40; // 图片高度
|
|
|
+ private static String IMAGE_FORMAT = "JPG";
|
|
|
+ private static Color[] COLORS = new Color[]{
|
|
|
+ new Color(0, 0, 255),
|
|
|
+ new Color(0, 255, 0),
|
|
|
+ new Color(255, 0, 0)
|
|
|
+ };
|
|
|
+ private static SecureRandom RANDOM = new SecureRandom();
|
|
|
+
|
|
|
+
|
|
|
+ public static Map<String, Object> generateVerifyCode(int verifySize, String sources) {
|
|
|
+ int codesLen = sources.length();
|
|
|
+ try {
|
|
|
+ StringBuilder verifyCode = new StringBuilder(verifySize);
|
|
|
+ for (int i = 0; i < verifySize; i++) {
|
|
|
+ verifyCode.append(sources.charAt(RANDOM.nextInt(codesLen - 1)));
|
|
|
+ }
|
|
|
+
|
|
|
+ BufferedImage image = createImage(verifyCode.toString());
|
|
|
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
|
|
+ ImageIO.write(image, IMAGE_FORMAT, outputStream);
|
|
|
+
|
|
|
+ byte[] data = outputStream.toByteArray();
|
|
|
+ String base64Image = Base64.getEncoder().encodeToString(data).replaceAll("[\\s*\t\n\r]", "");
|
|
|
+ outputStream.close();
|
|
|
+ Map<String, Object> returnData = new HashMap<>();
|
|
|
+ returnData.put("verifyCode", verifyCode);
|
|
|
+ returnData.put("verifyCodeImage", base64Image);
|
|
|
+ return returnData;
|
|
|
+ } catch (IOException e) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ private static BufferedImage createImage(String verifyCode) {
|
|
|
+ BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
|
|
|
+ Graphics graphics = image.getGraphics();
|
|
|
+
|
|
|
+ graphics.setColor(Color.WHITE);
|
|
|
+ graphics.fillRect(0, 0, WIDTH, HEIGHT);
|
|
|
+
|
|
|
+ int desX,desY,distance=16;
|
|
|
+ for (int i = 0; i < verifyCode.length(); i++) {
|
|
|
+ graphics.setColor(COLORS[RANDOM.nextInt(COLORS.length)]);
|
|
|
+ desX = (i+1)*distance;
|
|
|
+ desY = distance+RANDOM.nextInt(HEIGHT-2*distance);
|
|
|
+ graphics.drawString(Character.toString(verifyCode.charAt(i)),desX,desY);
|
|
|
+ }
|
|
|
+
|
|
|
+ for(int x=0;x<150;x++){
|
|
|
+ graphics.setColor(getRandomColor());
|
|
|
+ graphics.drawOval(RANDOM.nextInt(WIDTH),RANDOM.nextInt(HEIGHT),1,1);
|
|
|
+ }
|
|
|
+
|
|
|
+ graphics.dispose();
|
|
|
+ return image;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Color getRandomColor() {
|
|
|
+ int r = RANDOM.nextInt(256);
|
|
|
+ int g = RANDOM.nextInt(256);
|
|
|
+ int b = RANDOM.nextInt(256);
|
|
|
+ return new Color(r,g,b);
|
|
|
+ }
|
|
|
+}
|