فهرست منبع

生成头像时,使用自定义字体,防止字体缺失导致乱码

imndx 2 سال پیش
والد
کامیت
f2125a5baa

+ 28 - 8
src/main/java/cn/wildfirechat/app/avatar/AvatarServiceImpl.java

@@ -11,6 +11,8 @@ import org.springframework.util.StringUtils;
 import javax.annotation.PostConstruct;
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.nio.file.Files;
@@ -50,7 +52,7 @@ public class AvatarServiceImpl implements AvatarService {
     }
 
     @Override
-    public CompletableFuture<ResponseEntity<byte[]>> groupAvatar(GroupAvatarRequest request) throws IOException, URISyntaxException {
+    public CompletableFuture<ResponseEntity<byte[]>> groupAvatar(GroupAvatarRequest request) throws MalformedURLException {
         List<GroupAvatarRequest.GroupMemberInfo> infos = request.getMembers();
         List<URL> paths = new ArrayList<>();
         long hashCode = 0;
@@ -72,10 +74,12 @@ public class AvatarServiceImpl implements AvatarService {
             return CompletableFuture.supplyAsync(new Supplier<ResponseEntity<byte[]>>() {
                 @Override
                 public ResponseEntity<byte[]> get() {
+                    InputStream inputStream = null;
                     try {
                         GroupAvatarUtil.getCombinationOfHead(paths, file);
                         if (file.exists()) {
-                            byte[] bytes = StreamUtils.copyToByteArray(Files.newInputStream(file.toPath()));
+                            inputStream = Files.newInputStream(file.toPath());
+                            byte[] bytes = StreamUtils.copyToByteArray(inputStream);
                             return ResponseEntity.ok()
                                 .contentType(MediaType.IMAGE_PNG)
                                 .header("Cache-Control", "max-age=604800")
@@ -84,17 +88,33 @@ public class AvatarServiceImpl implements AvatarService {
                             return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
                         }
                     } catch (IOException | URISyntaxException e) {
-                        throw new RuntimeException(e);
+                        e.printStackTrace();
+                    } finally {
+                        if (inputStream != null) {
+                            try {
+                                inputStream.close();
+                            } catch (IOException e) {
+                                // do nothing
+                            }
+                        }
                     }
+                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
                 }
 
             });
         } else {
-            byte[] bytes = StreamUtils.copyToByteArray(Files.newInputStream(file.toPath()));
-            return CompletableFuture.completedFuture(ResponseEntity.ok()
-                .contentType(MediaType.IMAGE_PNG)
-                .header("Cache-Control", "max-age=604800")
-                .body(bytes));
+            try (
+                InputStream inputStream = Files.newInputStream(file.toPath())
+            ) {
+                byte[] bytes = StreamUtils.copyToByteArray(inputStream);
+                return CompletableFuture.completedFuture(ResponseEntity.ok()
+                    .contentType(MediaType.IMAGE_PNG)
+                    .header("Cache-Control", "max-age=604800")
+                    .body(bytes));
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+            return CompletableFuture.completedFuture(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
         }
     }
 

+ 18 - 4
src/main/java/cn/wildfirechat/app/avatar/GroupAvatarUtil.java

@@ -9,8 +9,10 @@ import java.awt.image.BufferedImage;
 import java.io.DataInputStream;
 import java.io.File;
 import java.io.IOException;
+import java.net.HttpURLConnection;
 import java.net.URISyntaxException;
 import java.net.URL;
+import java.net.URLConnection;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -147,12 +149,15 @@ public class GroupAvatarUtil {
      * @param bb       比例不对时是否需要补白
      */
     private static BufferedImage resize2(URL filePath, int height, int width,
-                                         boolean bb) throws URISyntaxException {
+                                         boolean bb) {
+        DataInputStream dis = null;
         try {
-            double ratio = 0; // 缩放比例
-
-            DataInputStream dis = new DataInputStream(filePath.openStream());
+            URLConnection urlConnection = filePath.openConnection();
+            urlConnection.setConnectTimeout(5 * 1000);
+            urlConnection.setReadTimeout(5 * 1000);
+            dis = new DataInputStream(urlConnection.getInputStream());
 
+            double ratio = 0; // 缩放比例
             //File f = new File(dis);
             BufferedImage bi = ImageIO.read(dis);
             Image itemp = bi.getScaledInstance(width, height,
@@ -191,6 +196,15 @@ public class GroupAvatarUtil {
             return (BufferedImage) itemp;
         } catch (IOException e) {
             e.printStackTrace();
+        } finally {
+            if (dis != null) {
+                try {
+                    dis.close();
+                } catch (IOException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+
         }
         return null;
     }

+ 17 - 1
src/main/java/cn/wildfirechat/app/avatar/NameAvatarBuilder.java

@@ -1,9 +1,12 @@
 package cn.wildfirechat.app.avatar;
 
+import org.springframework.core.io.ClassPathResource;
+
 import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
 
 import javax.imageio.ImageIO;
 
@@ -16,6 +19,8 @@ public class NameAvatarBuilder {
 
     private String fullName;
 
+    private static volatile Font font;
+
     public NameAvatarBuilder(String bgRGB) {
         templateImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
         templateG2D = templateImage.createGraphics();
@@ -28,7 +33,18 @@ public class NameAvatarBuilder {
     public NameAvatarBuilder name(String drawName, String fullName) {
         this.fullName = fullName;
         // Get the FontMetrics
-        Font font = templateG2D.getFont().deriveFont(40f);
+        // 加载自定义字体
+        if (font == null) {
+            try (InputStream inputStream = new ClassPathResource("fonts/simhei.ttf").getInputStream()) {
+                // 加载自定义字体
+                Font customFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
+                // 设置字体样式
+                font = customFont.deriveFont(Font.PLAIN, 40);
+            } catch (IOException | FontFormatException e) {
+                e.printStackTrace();
+            }
+        }
+
         FontMetrics metrics = templateG2D.getFontMetrics(font);
         // Determine the X coordinate for the text
         int x = (templateWidth - metrics.stringWidth(drawName)) / 2;

BIN
src/main/resources/fonts/simhei.ttf