我想根据使用Core Java的文本输入动态创建JPG图像



我正在尝试使用Graphics类在运行时创建图像。但是,尽管我有一个像line 1 n line 2这样的字符串,但我将文本写在图像上。

任何人可以在这方面为我提供例子吗?

要从字符串中删除线路断裂,您可以使用以下方法:

String str = "Line 1nLine 2";
str.replace(System.getProperty("line.separator"), "");

您可以使用BufferedImage类来创建图像:

// Create the target Font and a FontMetrics object for measuring the string's dimensions on the canvas
Font font = new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fm = new Canvas().getFontMetrics(font);
// Create a BufferedImage and obtain the Graphics object
BufferedImage img = new BufferedImage(fm.stringWidth(str), fm.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
// Draw the string at position (0|0)
g.setColor(Color.black);
g.drawString(str, 0, 0);

最新更新