public void createImage() {
try {
BufferedImage image = readImageFromResource("img/oss-share.png");
if (image == null) {{
throw new RuntimeException("图片读取失败");
}}
String text = "这是一行文字";
String text2 = "这是一行文字";
Graphics2D g2d = image.createGraphics();
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);
int x1 = (width - line1Width) / 2;
int y1 = height-70;
g2d.drawString(text, x1, y1);
int x2 = (width - line2Width) / 2;
int y2 =height-70;
g2d.drawString(text2, x2, y2 + 30);
g2d.dispose();
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编码的字符串
}