Use java para crear plantillas de texto de imagen

Escenario: Se acerca el cumpleaños del empleado, envíe un correo electrónico al colega que cumple años con una foto de bendición

El siguiente es el código para generar la plantilla de imagen.

package com.yujie;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageMergeExample {

    public static void main(String[] args) {
        try {
            // 加载背景图
            BufferedImage backgroundImage = ImageIO.read(new File("C:\\Users\\JAVA大师\\Desktop\\a.png"));

            // 创建一个新的 BufferedImage,大小与背景图相同
            BufferedImage combinedImage = new BufferedImage(
                    backgroundImage.getWidth(), backgroundImage.getHeight(), BufferedImage.TYPE_INT_ARGB);

            // 获取 Graphics2D 对象,用于绘制图像
            Graphics2D g2d = combinedImage.createGraphics();

            // 绘制背景图
            g2d.drawImage(backgroundImage, 0, 0, null);

            // 设置文字样式
            Font font = new Font("宋体", Font.PLAIN, 14); // 使用楷体字体
            Color textColor = Color.WHITE; // 替换为你的文本颜色

            // 在图像上绘制文字
            String text = "亲爱的马祖杰:@@" +
                    "去年今日,怀揣着理想和憧憬,你我相遇。@@" +
                    "你是否还记得,@@" +
                    "在海尔第-个帮助过你的同事;@@" +
                    "在海尔面临的第一个挑战;@@" +
                    "在海尔做的第一件引以为傲的事情。@@" +
                    "时光荏苒,我们已并肩奋斗365天,@@" +
                    "也曾迷茫,也曾彷徨,但你我不言放弃。@@" +
                    "感谢有你,风雨与共,让前进的步伐坚定而有力。@@" +
                    "因为有你,最暗的夜,也能看见最美的星光。  ";
            g2d.setFont(font);
            g2d.setColor(textColor);
            FontMetrics fontMetrics = g2d.getFontMetrics();

           // int x = (combinedImage.getWidth() - fontMetrics.stringWidth(text)) / 2;
            int x = 65;
            int y = 390 + fontMetrics.getAscent();

            String[] lines = text.split("@");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                g2d.drawString(line, x, y);
                y += fontMetrics.getHeight();
            }

            // 释放资源
            g2d.dispose();

            // 保存合并后的图像
            ImageIO.write(combinedImage, "PNG", new File("merged_image.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Representaciones:

Supongo que te gusta

Origin blog.csdn.net/qq_42058998/article/details/131799799
Recomendado
Clasificación