Pārlūkot izejas kodu

字符串转图片Base64字符串

andy 1 gadu atpakaļ
vecāks
revīzija
2c0544176a

+ 16 - 19
mainFactory/src/main/java/org/bfkj/utils/GenerateImage.java

@@ -12,7 +12,7 @@ import java.util.Map;
 
 public class GenerateImage {
     private static final int WIDTH = 120; // 图片宽度
-    private static final int HEIGHT = 40; // 图片高度
+    private static final int HEIGHT = 45; // 图片高度
     private static String IMAGE_FORMAT = "JPG";
     private static Color[] COLORS = new Color[]{
             new Color(0, 0, 255),
@@ -21,28 +21,22 @@ public class GenerateImage {
     };
     private static SecureRandom RANDOM = new SecureRandom();
 
+    public static String createCode(int size, String source){
+        StringBuilder verifyCode = new StringBuilder(size);
+        int codesLen = source.length();
+        for (int i = 0; i < size; i++) {
+            verifyCode.append(source.charAt(RANDOM.nextInt(codesLen - 1)));
+        }
+        return verifyCode.toString();
+    }
 
-    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();
+    public static String stringToImage(String code) throws IOException {
+        try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
+            BufferedImage image = createImage(code);
             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;
+            return "data:image/"+IMAGE_FORMAT+";base64," + Base64.getEncoder().encodeToString(data);
         }
     }
     private static BufferedImage createImage(String verifyCode) {
@@ -51,6 +45,9 @@ public class GenerateImage {
 
         graphics.setColor(Color.WHITE);
         graphics.fillRect(0, 0, WIDTH, HEIGHT);
+        Font font = graphics.getFont();
+
+        graphics.setFont(new Font(font.getFamily(),Font.BOLD,HEIGHT-10));
 
         int desX,desY,distance=16;
         for (int i = 0; i < verifyCode.length(); i++) {