From a8c9f2126cbef4c4a1f2d3c2098ccf52637bcdef Mon Sep 17 00:00:00 2001 From: wucongxing8150 <815046773@qq.com> Date: Fri, 1 Aug 2025 11:02:30 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E8=B7=AF=E5=BE=841?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../example/caseData/service/CertService.java | 3 ++- .../com/example/caseData/utils/ImageUtil.java | 23 +++++++++++-------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/example/caseData/service/CertService.java b/src/main/java/com/example/caseData/service/CertService.java index 8c4c421..952b016 100644 --- a/src/main/java/com/example/caseData/service/CertService.java +++ b/src/main/java/com/example/caseData/service/CertService.java @@ -18,6 +18,7 @@ import java.text.SimpleDateFormat; import java.io.File; import java.util.Date; import java.util.Objects; +import org.springframework.core.io.ClassPathResource; @Service public class CertService { @@ -34,7 +35,7 @@ public class CertService { ){ try { // 加载背景模板图片 - BufferedImage background = ImageIO.read(new File("static/cert/template.png")); + BufferedImage background = ImageIO.read(new ClassPathResource("static/cert/template.png").getInputStream()); Graphics2D g2d = (Graphics2D) background.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); diff --git a/src/main/java/com/example/caseData/utils/ImageUtil.java b/src/main/java/com/example/caseData/utils/ImageUtil.java index 4e21d94..d303018 100644 --- a/src/main/java/com/example/caseData/utils/ImageUtil.java +++ b/src/main/java/com/example/caseData/utils/ImageUtil.java @@ -1,19 +1,22 @@ package com.example.caseData.utils; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; +import org.springframework.core.io.ClassPathResource; + +import java.io.*; public class ImageUtil { public static byte[] readImageToBytes(String imagePath) throws IOException { - File file = new File(imagePath); - try (FileInputStream fis = new FileInputStream(file)) { - byte[] bytes = new byte[(int) file.length()]; - int read = fis.read(bytes); - if (read != bytes.length) { - throw new IOException("读取文件长度不一致"); + ClassPathResource resource = new ClassPathResource(imagePath); + try (InputStream inputStream = resource.getInputStream(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); } - return bytes; + + return outputStream.toByteArray(); } } }