Syed M Abbas Hashim
Syed M Abbas Hashim

Reputation: 17

How can I draw a text into a buffered image with different font affects in Java 2d?

I am trying to convert Multi-line Text to image but couldn't found a way to draw it with different Font format's is there any way to do it.Thanks in Advance.

Upvotes: 1

Views: 1629

Answers (1)

cocosushi
cocosushi

Reputation: 144

What you could do is simply loading an image, and then setting it as the default graphics context, and then drawing text with a Graphics2D object using different fonts. Here's how you could do this :

BufferedImage image = ImageIO.load(new File("test.png"));
Graphics2D g2d = image.createGraphics();
g2d.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
g2d.drawString("test", posx, posy, etc.)

If you want simply to draw to a blank image and then save it, just create a BufferedImage using the default constructor. Then, to save the image :

File output = new File("test.png");
ImageIO.write(image, "png", output);

If you want to know more about this, here's a link to Oracle's Java2D tutorials : https://docs.oracle.com/javase/tutorial/2d/images/drawonimage.html (from where these examples are).

Upvotes: 1

Related Questions