java写一个通过文字描述输出图片的代码
时间: 2023-03-19 19:22:29 浏览: 100
您好!以下是用 Java 编写一个通过文字描述输出图片的示例代码:
```java
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 TextToImage {
public static void main(String[] args) throws IOException {
String text = "这是一张图片";
int width = 200;
int height = 100;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLACK);
Font font = new Font("宋体", Font.BOLD, 20);
graphics.setFont(font);
graphics.drawString(text, 50, 50);
ImageIO.write(image, "png", new File("output.png"));
}
}
```
以上代码中,我们通过 `BufferedImage` 类创建了一个宽为 200,高为 100 的空白图片。然后,我们设置了背景色为白色,字体为黑色,将文字内容绘制在了图片中间。最后,我们将生成的图片保存为名为 "output.png" 的文件。
希望这个示例代码对您有所帮助!