This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to center a String within a JPEG?

 
Florian Heinisch
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13411
Firefox Browser Redhat VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ben Wood
Ranch Hand
Posts: 342
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ben Wood
Ranch Hand
Posts: 342
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and here is some example code:

 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic