3

Possible Duplicate:
Using Graphics2D to overlay text on a BufferedImage and return a BufferedImage

My Question is how to draw a String permanently to an image.

When I draw the String and then refresh the image the String is gone on the display.

Community
  • 1
  • 1
Tom
  • 503
  • 2
  • 13
  • what exactly is your context? Web application ? JFrame .... ? – MaVRoSCy Jul 14 '12 at 10:48
  • I agree with @MaVRoSCy. Your question is unanswerable as written. Please provide us with more information. – Hovercraft Full Of Eels Jul 14 '12 at 10:54
  • Oh, Im sorry about this. Im using Java Swing and a JFrame. Basically there are two Graphics objects. The first draws different stuff to an image and the second one draws the whole image on a JPanel in the JFrame. If more information is needed I will of course provide it. – Tom Jul 14 '12 at 11:05
  • 1
    Perhaps like [this](http://stackoverflow.com/a/2658663/230513)? – trashgod Jul 14 '12 at 13:28
  • 1
    @trashgod: Yes it seems to be the same method as Andrew Thompson described. Thanks to all of you! – Tom Jul 14 '12 at 13:56

2 Answers2

5

..how to draw a String permanently to an image.

If you mean a BufferedImage then it is simple.

  1. Get a Graphics or Graphics2D instance from the image.
  2. Draw the string to it.
  3. Dispose of the graphics object.

The job is done. To display the image, add it to a label.

If you have an Image instance as opposed to a BufferedImage instance, create a buffered image as large as the original image, then paint it to the graphics instance before step 2. (draw the string) above.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

In order to make the text always show on top of the image, place your drawString call inside paint(Graphics g)

It would be helpful if you posted some of your code, but I think you are probably calling drawString from the wrong place. Now if you also want to save the image with the text on top, that is another matter. I would probably use javax.imageio.ImageIO.write for that.

Thorn
  • 4,015
  • 4
  • 23
  • 42
  • Thank you very much for taking your time! I know about this solution as a workaround. I thought there might be an efficient solution modifying the image directly instead of just drawing the String again and again but it seems there isnt. Still thanks! – Tom Jul 14 '12 at 13:36
  • You can modify the image directly. Look at the methods in `java.awt.image.BufferedImage` and you will notice you can call getGraphics() or createGraphics() If you store your image as BufferedImage you can modify it (adding text) through the graphics context. – Thorn Jul 14 '12 at 15:59