用Java将文本写入图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2736320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:17:28 来源:igfitidea点击:
Write text onto image in Java
提问by n002213f
Is there a Java library to write text to images, same as PHP's GD library.
是否有一个 Java 库可以将文本写入图像,与 PHP 的GD 库相同。
回答by Etaoin
Sure. First load the image, probably using a method of ImageIO
. Then, using a Graphics
object representing the image itself, call the drawString
method.
当然。首先加载图像,可能使用ImageIO
. 然后,使用Graphics
表示图像本身的对象,调用该drawString
方法。
回答by Bozho
回答by Joshua Fox
Take a look at Graphics2D.drawString
回答by Perumal Ramasamy
Try the below code
试试下面的代码
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Testing {
public static void main(String arg[]) throws IOException {
String key = "Sample";
BufferedImage bufferedImage = new BufferedImage(170, 30,
BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.LIGHT_GRAY);
graphics.fillRect(0, 0, 200, 50);
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial Black", Font.BOLD, 20));
graphics.drawString(key, 10, 25);
ImageIO.write(bufferedImage, "jpg", new File(
"C:/Users/admin/desktop/image.jpg"));
System.out.println("Image Created");
}
}