使用Java在图像上写多行文本

使用Java在图像上写多行文本

本文介绍了使用Java在图像上写多行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了java.awt.Graphics文档,stackoverflow找不到解决方案.我在输入中有两件事,一个图像文件和多行文本(段落).我需要在图像文件上写多行文本,然后将其另存为新图像.想知道我是否在这里错过了一些非常简单的事情.我也愿意使用任何好的第三方库.

I looked at java.awt.Graphics documentation, stackoverflow, could not find a solution. I have in input two things, an image file and the multi line text (paragraph). I need to write the multi line text on the image file and then save it as a new image. Wondering if I am missing something really simple here.I am open to using any good third party libraries as well.

final BufferedImage image = ImageIO.read(new File("c:/anil/Lenna.png"));

    Graphics g = image.getGraphics();
    g.setFont(g.getFont().deriveFont(30f));
    g.drawString("Hello world", 100, 100);
    g.dispose();

上面的代码仅在图像上写一行.

Above code writes just a single line on the image.

推荐答案

如果要绘制多条线,则必须显式地执行此操作...

if you want to draw several lines you have to do it explicitly...

所以第一步是检测"线

String str = ... //some text with line breaks;
String [] lines = str.spilt("\n"); //breaking the lines into an array

第二步是绘制所有线条

Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
int lineHeight = g.getFontMetrics().getHeight();
//here comes the iteration over all lines
for(int lineCount = 0; lineCount < lines.length; lineCount ++){ //lines from above
    int xPos = 100;
    int yPos = 100 + lineCount * lineHeight;
    String line = lines[lineCount];
    g.drawString(line, xpos, yPos);
}
g.dispose();

这篇关于使用Java在图像上写多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:32