How can I load an image and write text to it using Java?

10,842

Solution 1

Try this way:

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public class ImagingTest {

    public static void main(String[] args) throws IOException {
        String url = "http://icomix.eu/gr/images/non-batman-t-shirt-gross.jpg";
        String text = "Hello Java Imaging!";
        byte[] b = mergeImageAndText(url, text, new Point(200, 200));
        FileOutputStream fos = new FileOutputStream("so2.png");
        fos.write(b);
        fos.close();
    }

    public static byte[] mergeImageAndText(String imageFilePath,
            String text, Point textPosition) throws IOException {
        BufferedImage im = ImageIO.read(new URL(imageFilePath));
        Graphics2D g2 = im.createGraphics();
        g2.drawString(text, textPosition.x, textPosition.y);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(im, "png", baos);
        return baos.toByteArray();
    }
}

Solution 2

Use ImageIO to read the image into a BufferedImage.

Use the getGraphics() method of BufferedImage to get the Graphics object.

Then you can use the drawString() method of the Graphics object.

You can use ImageIO to save the image.

Solution 3

I'm just going to point you in the general direction of image manipulation in Java.

To load images you can use ImageIO. You can also use ImageIO to output images to different formats.

The easiest way to create an image is to use BufferedImage and then paint on it via Graphics2D. You can use Graphics2D to paint your loaded image and then paint your text on top of it.

When you're done you use ImageIO to output the image in a suitable format (PNG, JPG, etc).

Share:
10,842
mohamede1945
Author by

mohamede1945

Updated on July 09, 2022

Comments

  • mohamede1945
    mohamede1945 almost 2 years

    I've an image located at images/image.png in my java project. I want to write a method its signature is as follow

    byte[] mergeImageAndText(String imageFilePath, String text, Point textPosition);

    This method will load the image located at imageFilePath and at position textPosition of the image (left upper) I want to write the text, then I want to return a byte[] that represents the new image merged with text.