aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes How to center a String within a JPEG? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to center a String within a JPEG?" Watch "How to center a String within a JPEG?" New topic
Author

How to center a String within a JPEG?

Florian Heinisch
Greenhorn

Joined: Mar 03, 2005
Posts: 15
Hi all,
I am developing a Servlet where I read in an image on which I want to place some text exactly into the center of the image.

Is there a convenient way to center the text (horizontally and vertically) according to the jpeg's size? Or do I have to count the String's characters, check the font's size and calculate the String's x- and y-position to center the text?
Thanks for any hints!
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Sure you didn't mean "Applet".
"g.drawString("Test", 100, 100);"

You can't draw a string on a servlet because it has no graphical elements.


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ben Wood
Ranch Hand

Joined: Aug 14, 2001
Posts: 342
True, but the BufferedImage object can provide a graphics context that can be drawn upon, and you can then set the content type to an image format so the servlet delivers the image to the browser. I do this quite a lot.

Florian, take a look at java.awt.FontMetrics stringWidth() method. This will tell you how wide the string actually is and you can then do some simple maths based on the width of the BufferedImage (which has getWidth() method) to determine where to draw it to make it centred.

hope this helps!
[ March 09, 2005: Message edited by: Ben Wood ]

SCJP 1.4, www.gsi3d.org.uk
Ben Wood
Ranch Hand

Joined: Aug 14, 2001
Posts: 342
and here is some example code:

David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

while this is nested in a Servlet, the actual question is more AWTish than Servlety, so off to AWT you go

Dave
Florian Heinisch
Greenhorn

Joined: Mar 03, 2005
Posts: 15
Hey Ben Wood,

thanks a lot for your answer. I kept searching the JAVA API for quite some time before posting here - unfortunately I did not "discover" the FontMetrics stringWidth() method.
Thank you so much, you helped me a lot!

@David: I was not quite sure whether to post in the AWT or in the SERVLETS forum ... thanks for moving the question to the right place!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to center a String within a JPEG?