Qwerty
Qwerty

Reputation: 140

Positioning of text to image in java

I have written a code to convert a text in a .txt file to a .jpeg image. But my problem lies here: I have used the drawstring function and it gives me access to only the coordinates of the bottom left corner of the text in the image. The code is :

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;
import java.awt.font.*;
import java.awt.geom.*;

class TextToImageDemo
{

    public static void main(String[] args) throws IOException
    {
       String sampleText = "SAMPLE TEXT",s="ALPHA";
       BufferedReader br = null;
        try
            {
                br = new BufferedReader(new FileReader("E:\\Java\\file.txt"));

                while ((sampleText = br.readLine()) != null)
                   {
                        System.out.println(sampleText);
                        s=sampleText;
                   }
            }
        catch (IOException e)
            {
                e.printStackTrace();
            }
        finally
            {
                try
                    {
                        if (br != null)br.close();
                    }
                catch (IOException ex)
                    {
                        ex.printStackTrace();
                    }
            }


        String fileName = "Image";

        File newFile= new File("./" + fileName + ".jpeg");

        Font font = new Font("Stencil", Font.PLAIN, 100);

        FontRenderContext frc = new FontRenderContext(null, true, true);

        BufferedImage image = new BufferedImage(2000, 200,   BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();
        System.out.println(s);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 2000, 200);
        g.setColor(Color.BLACK);
        g.setFont(font);

        g.drawString(s, 800,150);       
        g.dispose();

      try
          {
              FileOutputStream fos = new FileOutputStream("E:\\Java\\1111.jpg");
              ImageIO.write(image,"jpg",fos);
              fos.close();
          }
      catch(Exception ex)
          {
              ex.printStackTrace();
          }

    }
}

What I want is to centralize the text in the .txt file(whatever the length of the text be). The background should be fixed (2000 x 200). And the text should be in the centre. How am I to achieve that using only the bottom left coordinates (given by the drawstring function)?

A few specifications about the text: it is a single line text with maximum number of words =30.

Upvotes: 0

Views: 61

Answers (1)

gpasch
gpasch

Reputation: 2672

Use font metrics:

FontMetrics fm=g.getFontMetrics();
Rectangle r=new Rectangle(fm.getStringBounds(s, g).getBounds());
g.drawString(s, image.getWidth()/2-r.width/2, image.getHeight()/2-r.height/2);

Upvotes: 1

Related Questions