import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class CoverGenerator {
public static void generateCover(String name, String outputPath) {
// A4纸的分辨率 (300 DPI)
int width = 2480;
int height = 3508;
// 创建一个空白图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
// 设置奶黄色背景颜色
Color paleYellow = new Color(255, 253, 208);
g2d.setColor(paleYellow);
g2d.fillRect(0, 0, width, height);
// 设置字体样式为楷书风格,颜色为红色
g2d.setFont(new Font("楷体", Font.BOLD, 200));
g2d.setColor(Color.RED);
// 测量名字的宽度和高度,以便居中显示
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D rect = fm.getStringBounds(name, g2d);
// 计算名字的起始位置
int x = (width - (int) rect.getWidth()) / 2;
int y = height / 4 + fm.getAscent(); // 将名字放置在高度的1/4位置
// 绘制名字
g2d.drawString(name, x, y);
// 释放资源
g2d.dispose();
try {
// 将图片保存到指定路径
ImageIO.write(image, "png", new File(outputPath));
System.out.println("封面生成成功:" + outputPath);
} catch (Exception e) {
System.err.println("封面生成失败:" + e.getMessage());
}
}
public static void main(String[] args) {
// 示例调用
generateCover("Java 大佬", "C:\\Users\\Administrator\\Desktop\\cover.png");
}
}