Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 621
mohamede1945 Avatar asked Nov 16 '25 23:11

mohamede1945


2 Answers

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();
    }
}
like image 118
Rekin Avatar answered Nov 19 '25 13:11

Rekin


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.

like image 20
camickr Avatar answered Nov 19 '25 13:11

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!