gpt4 book ai didi

Java:绘制文本最快的方法?

转载 作者:行者123 更新时间:2023-11-30 03:09:22 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,仅用文本创建图像(例如,在白色方 block 上写“你好”并存储图像),这听起来很简单,但必须快速完成。我尝试了 Java2D 库,但在 BufferedImage 上绘图需要大约 2 秒才能绘制图像,甚至不保存或显示它。我还尝试过基于 Java 的验证码生成器,但它们花费的时间太长(5 秒)。

这似乎是一个足够简单的任务,只需绘制文本即可,但我很沮丧,因为我无法以超过 2 秒的速度完成此任务。

有没有办法可以通过一些命令行选项(例如分配更多内存或优先级)在我的计算机上更快地完成此操作?是否有我应该使用的特定 Java 库,或者我应该注意 Java2D 的一些奇怪的怪癖以使事情变得更快?

这是我的整个程序。我在 Eclipse 中运行这个:

import java.awt.*;
import java.awt.image.BufferedImage;

public class SimpleGraphics {
public static void main(String[] args) {
long time = System.currentTimeMillis();

String message = "Hello world";
int width = 100;
int height = 100;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

Graphics2D graphics = img.createGraphics();
graphics.setColor(Color.black);
graphics.setFont(new Font("TimesRoman", Font.BOLD, 12));

FontMetrics fontMetrics = graphics.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();

graphics.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4);
System.out.println(System.currentTimeMillis() - time); //consistently ~2 seconds
}
}

最佳答案

我从命令行运行代码(在 Windows 7 上使用 JDK8),大约需要 300 毫秒。

我将您的代码修改为以下内容:

import java.awt.*;
import java.awt.image.BufferedImage;

public class SimpleGraphics {
public static void main(String[] args) {
long time = System.currentTimeMillis();

for (int i = 0; i < 100; i++)
createImage();

System.out.println(System.currentTimeMillis() - time); //consistently ~2 seconds
}

public static void createImage()
{
String message = "Hello world";
int width = 100;
int height = 100;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

Graphics2D graphics = img.createGraphics();
graphics.setColor(Color.black);
graphics.setFont(new Font("TimesRoman", Font.BOLD, 12));

FontMetrics fontMetrics = graphics.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();

graphics.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4);
}
}

我仍然得到大约 300 毫秒。

所以问题不在于绘画代码。

我不知道为什么你会得到 2 秒,但加载类显然会产生一些开销。因此,我所能建议的就是分批进行图像创建,以最大限度地缩短时间。

关于Java:绘制文本最快的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33943574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com