--- miscJava/Test3/src/ImageServlet.java 2010/02/22 21:21:10 610 +++ miscJava/Test3/src/ImageServlet.java 2010/02/22 22:18:40 611 @@ -1,10 +1,16 @@ import java.awt.Color; +import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; +import java.awt.font.LineMetrics; +import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; +import java.io.File; import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletException; @@ -17,7 +23,23 @@ // Image scaling :http://helpdesk.objects.com.au/java/how-do-i-scale-a-bufferedimage public class ImageServlet extends HttpServlet { private static final long serialVersionUID = 1L; + + Logger logger = Logger.getLogger(ImageServlet.class.getName()); + protected Font loadFont() throws IOException { + File fontFile= new File( getServletContext().getRealPath("/Comic_Sans_MS.ttf") ); + logger.info( "Font:" + fontFile.getAbsolutePath() ); + + Font font = null; + try { + font = Font.createFont(Font.TRUETYPE_FONT, fontFile); + } catch (Exception ex) { + logger.log(Level.SEVERE, "Font load failed", ex); + } + + + return font.deriveFont(48.0f); + } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -30,6 +52,24 @@ gfx.fillRect(0, 0, width, height); //Graphics2D has many various drawing methods gfx.setColor( Color.blue ); gfx.fillOval(10, 10, width-20, height-20); + gfx.setColor( Color.black ); + + ///////////////////// + ///Text draw section + String text = "Text to draw"; + Font f = loadFont(); + gfx.setFont( f ); + Rectangle2D bounds = f.getStringBounds(text, gfx.getFontRenderContext()); + int textX = (int) (width-bounds.getWidth())/2; + + + logger.info("bWidth=" + bounds.getWidth() + ", bHeight=" + bounds.getHeight()); + + + gfx.drawString(text, textX, 210); + + + gfx.dispose(); //dispose when we are done with drawing