开发者

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

开发者 https://www.devze.com 2023-03-16 08:23 出处:网络
I\'ve an image located at images/image.png in my java project. I want to write a method its signature is as follow

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 imageFi开发者_Python百科lePath, 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.


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();
    }
}


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消