图像上的大胆文字

时间:2013-05-28 09:58:34

标签: java image bufferedimage

我想在图片上添加粗体文字,只有选中的文字应为粗体。

String word =“这是虚拟文字,应该是 BOLD

final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));

3 个答案:

答案 0 :(得分:2)

您想使用AttributedString并将其iterator传递给drawString

static String Background = "input.png";
static int curX = 10;
static int curY = 50;

public static void main(String[] args) throws Exception {
    AttributedString word= new AttributedString("This is text. This should be BOLD");

    word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.PLAIN, 18));
    word.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);

    // Sets the font to bold from index 29 (inclusive)
    // to index 33 (exclusive)
    word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.BOLD, 18), 29,33);
    word.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 29,33);

    final BufferedImage image = ImageIO.read(new File(Background));
    Graphics g = image.getGraphics();
    g.drawString(word.getIterator(), curX, curY);
    g.dispose();
    ImageIO.write(image, "png", new File("output.png"));
}

output.png:

This is text. This should be BOLD

答案 1 :(得分:1)

您可以在绘制字符串之前在Graphics对象上设置Font,如下所示:

Font test = new Font("Arial",Font.BOLD,20);

g.setFont(test);

如果你只想要一个单词加粗,你必须两次调用drawString,并且只在第二次将字体设置为粗体。

答案 2 :(得分:0)

也许这个会有所帮助 - curX,curY应该在第一个drawString之后更新,否则看起来会很讨厌。 :)

String word="This is text, this should be ";
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
Font f = new Font("TimesRoman", Font.Bold, 72);
g.setFont(f);
String word="BOLD";
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));
相关问题