Java write text to image, then write to output file

I have an image on top of which I would like to write text that has several lines, is aligned in the center and dynamic (variable width). I tried using the method drawStringfrom Graphics, but I could not get the centering and dynamic positioning to work. I am currently writing in the library swingusing JLabelsand the like, but it is difficult for me to find a relatively simple approach to this. I would also like the last image to be written to a file, but it seems that mixing ImageIOwith JPaneldoes not work very well. I only get a black box at the moment. If anyone could even provide a simple outline of how to approach this, I would really appreciate it.

Thank!


Sorry, I had to be more specific .. I would like the text itself to be centered (since it should line up in the middle of each line), instead of placing the text in the center of the image, the text will be placed in another place in the image, not in the middle. Again, I apologize for the fuzzy descriptions. Thank!

+5
source share
3 answers

You really don't need to download if you just want to generate image files.

You can do something like this:

import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;

BufferedImage img = ImageIO.read(new File("dog.jpg")); // try/catch IOException
int width = img.getWidth();
int height = img.getHeight();

BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();

// draw graphics
g2d.drawImage(img, 0, 0, null);
g2d.drawString(text, x, y);

g2d.dispose();

try {

// Save as PNG
File file = new File("newimage.png");
ImageIO.write(bufferedImage, "png", file);

// Save as JPEG
file = new File("newimage.jpg");
ImageIO.write(bufferedImage, "jpg", file);

} catch (IOException e) { }

For more information see:

http://www.exampledepot.com/egs/javax.imageio/Graphic2File.html

Text alignment and alignment can be done using the FontMetrics class.

+8

drawString().

, :

Font font = getFont();
FontMetrics metrics = getFontMetrics( font );
int width = metrics.stringWidth( theString );

-Djava.awt.headless=true, ( GUI).

+2

JLabel :

JLabel picture = new JLabel( new ImageIcon(...) );
picture.setText("<html><center>Text<br>over<br>Image<center></html>");
picture.setHorizontalTextPosition(JLabel.CENTER);
picture.setVerticalTextPosition(JLabel.CENTER);

Screen Image .

Edit:

, . , . , :

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class LabelImageText extends JPanel
{
    public LabelImageText()
    {
        JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
        label1.setText( "Easy Way" );
        label1.setHorizontalTextPosition(JLabel.CENTER);
        label1.setVerticalTextPosition(JLabel.CENTER);
        add( label1 );

        //

        JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
        label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
        add( label2 );

        JLabel text = new JLabel( "More Control" );
        text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        label2.add( Box.createVerticalGlue() );
        label2.add( text );
        label2.add( Box.createVerticalStrut(10) );

        //

        JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
        add( label3 );

        JLabel text3 = new JLabel();
        text3.setText("<html><center>Text<br>over<br>Image<center></html>");
        text3.setLocation(20, 20);
        text3.setSize(text3.getPreferredSize());
        label3.add( text3 );

        //

        JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
        add( label4 );

        JTextPane textPane = new JTextPane();
        textPane.setText("Add some text that will wrap at your preferred width");
        textPane.setEditable( false );
        textPane.setOpaque(false);
        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        StyledDocument doc = textPane.getStyledDocument();
        doc.setParagraphAttributes(0, doc.getLength(), center, false);
        textPane.setBounds(20, 20, 75, 100);
        label4.add( textPane );
    }

    public static class ColorIcon implements Icon
    {
        private Color color;
        private int width;
        private int height;

        public ColorIcon(Color color, int width, int height)
        {
            this.color = color;
            this.width = width;
            this.height = height;
        }

        public int getIconWidth()
        {
            return width;
        }

        public int getIconHeight()
        {
            return height;
        }

        public void paintIcon(Component c, Graphics g, int x, int y)
        {
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("LabelImageText");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new LabelImageText() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
+2

All Articles