From 50164d95bfe34f532e3f2513a53f62c0864fe1a2 Mon Sep 17 00:00:00 2001 From: zhuo <2089219845@qq.com> Date: 星期三, 07 五月 2025 18:11:31 +0800 Subject: [PATCH] 关闭流 --- ruoyi-common/src/main/java/com/ruoyi/common/utils/SignatureImageUtil.java | 66 +++++++++++++++++++++++++++++++++ 1 files changed, 66 insertions(+), 0 deletions(-) diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/SignatureImageUtil.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/SignatureImageUtil.java new file mode 100644 index 0000000..15365c4 --- /dev/null +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/SignatureImageUtil.java @@ -0,0 +1,66 @@ +package com.ruoyi.common.utils; + +import org.springframework.core.io.ClassPathResource; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.font.FontRenderContext; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.io.*; + +/** + * @Author zhuo + * @Date 2025/5/7 + */ +public class SignatureImageUtil { + + /** + * 鏍规嵁涓枃瀵煎嚭绛惧悕鍥剧墖 + * @param text + * @return + * @throws IOException + * @throws FontFormatException + */ + public static InputStream saveImageToFile(String text){ + // 鑾峰彇瀛椾綋搴� + Font font = null; + try (InputStream is = new ClassPathResource("/ttf/signature.ttf").getInputStream()) { + font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(50f); + } catch (FontFormatException | IOException e) { + throw new RuntimeException(e); + } + + int width = 100; // 鍥剧墖鐨勫搴� + int height = 50; // 鍥剧墖鐨勯珮搴� + + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D g2d = image.createGraphics(); + + g2d.setFont(font); + + // 璁剧疆鏂囧瓧棰滆壊涓洪粦鑹� + g2d.setColor(Color.black); + + // 璁剧疆鏂囧瓧鍦ㄥ浘鐗囦腑鐨勪綅缃� + FontRenderContext context = g2d.getFontRenderContext(); + Rectangle2D bounds = font.getStringBounds(text, context); + double x = (width - bounds.getWidth()) / 2; + double y = (height - bounds.getHeight()) / 2; + double ascent = -bounds.getY(); + double baseY = y + ascent; + g2d.drawString(text, (int) x, (int) baseY); + g2d.dispose(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + try { + ImageIO.write(image, "png", os); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return new ByteArrayInputStream(os.toByteArray()); + } + +} -- Gitblit v1.9.3