如何使用Java加载图像并将文本写入其中? [英] How can I load an image and write text to it using Java?

查看:111
本文介绍了如何使用Java加载图像并将文本写入其中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的java项目中有一个位于images / image.png的图像。我想编写一个方法,其签名如下:

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

此方法将加载位于 imageFilePath 和位置的图像图像的textPosition (左上)我想写文本,然后我想返回一个表示合并的新图像的byte []带文字。

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.

推荐答案

试试这种方式:

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

这篇关于如何使用Java加载图像并将文本写入其中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆