Software Technology Tips

This tip describes how text can be converted to image using Java awt..  
Step1: Create a String which we will convert to image
Step2: Create a BufferedImage
Step3: Create get the height and width of the String
Step4: call the createGraphics(), which draws the BufferedImage object to Graphics2D object
Step6: set the font color, backgroung color etc as required


class TextToImageDemo{
public static void main(String[] args) throws IOException{
        //create String object to be converted to image
       String sampleText = "SAMPLE TEXT";
        //Image file name
       String fileName = "Image";
        //create a File Object
        File newFile = new File("./" + fileName + ".jpeg");
        //create the font you wish to use
        Font font = new Font("Tahoma", Font.PLAIN, 11);
        //create the FontRenderContext object which helps us to measure the text
        FontRenderContext frc = new FontRenderContext(null, true, true);
        //get the height and width of the text
        Rectangle2D bounds = font.getStringBounds(sampleText, frc);
        int w = (int) bounds.getWidth();
        int h = (int) bounds.getHeight();
        //create a BufferedImage object
       BufferedImage image = new BufferedImage(w, h,   BufferedImage.TYPE_INT_RGB);
        //calling createGraphics() to get the Graphics2D
        Graphics2D g = image.createGraphics();
        //set color and other parameters
        g.fillRect(0, 0, w, h);
       g.drawString(sampleText, (float) bounds.getX(), (float) -bounds.getY());
      //releasing resources
        //creating the file
       ImageIO.write(image, "jpeg", fileName);

Related Tags:


Author: Partho Banerjee

Related Pages

  • Java Swing/Netbeans Development
  • Java Web Projects


Let us Connect!

Awards and Achievements

Red Herringcolor DeloitteFast50 DB ZInnov1   Nascome  DB Stpi

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login