Java项目,在图片上生成文字(文字居中且底部对齐)

public void createImage() {

try {
            // 读取资源文件中的图片
            BufferedImage image = readImageFromResource("img/oss-share.png");
            if (image == null) {{
                throw new RuntimeException("图片读取失败");
            }}
          
            // 在图片上绘制文本
            String text = "这是一行文字";
            String text2 = "这是一行文字";

            // 创建Graphics2D对
            Graphics2D g2d = image.createGraphics();
            // 设置字体和颜色
            // 加载思源黑体字体

            // 通过类加载器获取字体文件的输入流,路径相对于resources目录
            // 1. 加载字体
            InputStream fontInputStream = ImageUtils.class.getResourceAsStream("字体路径");
            Font customFont = Font.createFont(Font.TRUETYPE_FONT, fontInputStream);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont(customFont);

            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setFont(customFont.deriveFont(Font.PLAIN, 24f));
            // 第一行文字内容
            // 测量第一行文字宽度
            int line1Width = g2d.getFontMetrics().stringWidth(text);

            // 第二行文字内容
            // 测量第二行文字宽度
            int width = image.getWidth();
            int height = image.getHeight();
            int line2Width = g2d.getFontMetrics().stringWidth(text2);

            // 计算整体文字宽度,取较宽的那一行作为参考来确定居中的x坐标
            int x1 = (width - line1Width) / 2;

            // 确定文字的y坐标,放置在图片靠下位置,这里假设距离底部30像素,可按需调整
            int y1 = height-70;

            // 绘制第一行文字
            g2d.drawString(text, x1, y1);
            // 计算整体文字宽度,取较宽的那一行作为参考来确定居中的x坐标
            int x2 = (width - line2Width) / 2;
            // 确定文字的y坐标,放置在图片靠下位置,这里假设距离底部30像素,可按需调整
            int y2 =height-70;
            // 调整y坐标绘制第二行文字
            g2d.drawString(text2, x2, y2 + 30);  // 两行文字间隔25像素,可调整
            // 释放资源
            g2d.dispose();
            // 将处理后的图片转换为Base64编码的字符串
            return convertToBase64(image);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FontFormatException e) {
            throw new RuntimeException(e);
        }
        return null;


}
 private static String convertToBase64(BufferedImage image) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream); // 将图片写入输出流
        byte[] imageBytes = outputStream.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes); // 转换为Base64编码的字符串
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大伟攀高峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值