How to add a line and text to a buffered image?

Posted on 2006-04-28
Last Modified: 2012-05-05
I have a buffered image that I am going to print.  

Given the buffered image object, what is the easiest way to:

add a line of text at the top
add a line going accross the width of the page
center the original buffered image underneath that?
Question by:jjacksn
    LVL 14

    Expert Comment

    by:Tommy Braas
    Create a new image. Draw the texts as you wish. Finally draw the old image as desired. Print the new image!
    LVL 5

    Author Comment

    Any sample code on drawing fonts?  (I don't know how).
    LVL 14

    Accepted Solution

    LVL 5

    Author Comment

    yeah, actually, turns out I do have acces to a graphics object where I need it, making this much easier.  happen to know how to center text?
    LVL 15

    Assisted Solution

    > happen to know how to center text?

    Use : drawString(String s, float x, float y) - Float X and Y is the possition use to place where on the screen you would like it to be. :)
    LVL 14

    Expert Comment

    by:Tommy Braas
    >> happen to know how to center text?
    You would have to calculate the length of the text, using the font information, and the use the length to position the text appropriately.
    LVL 23

    Expert Comment

    LVL 5

    Assisted Solution

    Here is a working sample application...

    Let me know if you have any questions..



    import javax.imageio.ImageIO;
    import javax.swing.JTextField;
    import java.awt.*;
    import java.awt.image.*;

    public class TextOnImage
          public BufferedImage loadImage(String path) throws IOException
                Image img = File(path));
                return (BufferedImage)img;
          public void saveImage(String path, BufferedImage img) throws IOException
                ImageIO.write(img, "PNG", new File(path));
          public int getStringWidth(String str, Font f)
                JTextField txt = new JTextField();
                FontMetrics fm = txt.getFontMetrics(txt.getFont());
                return fm.stringWidth(str);
          public void drawText(String text, BufferedImage img)
                //Create a graphics object
                Graphics2D g2d = (Graphics2D)img.createGraphics();
                //create a font
                Font f = new Font("Arial", Font.BOLD, 14);
                //determine the total width of the string to be written
                double stringWidth = getStringWidth(text, f);
                //turn on anitaliasing (smooth edges)
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //determine the x coordinate to center the string
                double imageWidth = img.getWidth();
                int x = (int)Math.floor((imageWidth-stringWidth)/(double)2);
                int y = 20;
                //create a color
                Color c = Color.BLACK;
                g2d.drawString(text, x, y);
          public static void main(String[] args) throws IOException
                TextOnImage toi = new TextOnImage();
                BufferedImage img = toi.loadImage("C:/sample.jpg");
                toi.drawText("Hello World!", img);

    LVL 86

    Assisted Solution

    This might help if you adapted it:

          class OverlayIcon extends ImageIcon {
                private String text;

                private boolean saved;

                 * @param image
                public OverlayIcon(Image image, String text) {
                      this.text = text;

                 * (non-Javadoc)
                 * @see javax.swing.ImageIcon#paintIcon(java.awt.Component,
                 *      java.awt.Graphics, int, int)
                public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
                      super.paintIcon(c, g, x, y);
                      g.drawString(text, 10, 10);

                public void saveOverlay() {
                      Graphics g = null;
                      try {
                            BufferedImage bi = new BufferedImage(getIconWidth(), getIconHeight(),
                            g = bi.getGraphics();
                            paintIcon(component, g, 0, 0);
                            ImageIO.write(bi, "bmp", new File("overlay.bmp"));
                      } catch (IOException e) {
                      } finally {


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Suggested Solutions

    Title # Comments Views Activity
    Java MSI Solution 3 51
    Fibonacci challenge 11 61
    changeXy challenge 13 40
    wordcount challenge 11 46
    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
    Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now