简体   繁体   English

如何使用 Java 加载图像并向其写入文本?

[英]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.我的 java 项目中有一个位于 images/image.png 的图像。 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.此方法将加载位于imageFilePath和 position 的图像textPosition图像(左上角) 我想写text ,然后我想返回一个 byte[] 表示与文本合并的新图像。

Use ImageIO to read the image into a BufferedImage .使用ImageIO将图像读入BufferedImage

Use the getGraphics() method of BufferedImage to get the Graphics object.使用BufferedImagegetGraphics()方法获取 Graphics object。

Then you can use the drawString() method of the Graphics object.然后就可以使用Graphics object的drawString()方法了。

You can use ImageIO to save the image.您可以使用ImageIO来保存图像。

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

I'm just going to point you in the general direction of image manipulation in Java.我将在 Java 中向您指出图像处理的一般方向。

To load images you can use ImageIO .要加载图像,您可以使用ImageIO You can also use ImageIO to output images to different formats.您还可以使用 ImageIO 将 output 图像转换为不同的格式。

The easiest way to create an image is to use BufferedImage and then paint on it via Graphics2D .创建图像的最简单方法是使用BufferedImage ,然后通过Graphics2D在其上绘制。 You can use Graphics2D to paint your loaded image and then paint your text on top of it.您可以使用 Graphics2D 绘制加载的图像,然后在其上绘制文本。

When you're done you use ImageIO to output the image in a suitable format (PNG, JPG, etc).完成后,您使用 ImageIO 将图像转换为合适的格式(PNG、JPG 等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM