Java2D&形象创作

发布于 2024-09-10 03:04:03 字数 285 浏览 6 评论 0原文

我想从 Java 动态创建一些图像并将其保存到文件中。 正如我在各种教程中阅读的那样,我需要使用 BufferedImage。

但是,BufferedImage 构造函数需要高度和宽度作为参数。但我不知道图像的最终尺寸。我应该如何创建预先未知尺寸的图像?

有两种明显的策略:

  1. 首先创建一个非常大的图像,例如 10000x10000。
  2. 逐渐创建更大的图像,并将原始图像复制到其中。缺点是每次我想添加一些东西之前我都需要检查边界。

你如何处理这个问题?

I want to dynamically create some image from Java and save it to a file.
As I read in various tutorials, I need to use BufferedImage.

But, the BufferedImage constructor requires that the height and width as parameters. But I don't know the final size of my image. How should I create an image with size unknown in advance?

There are two obvious strategies:

  1. Create a very large image initially, say 10000x10000.
  2. Gradually creating larger image, and copying the original to it. The drawback is that I need to check the bounds before each time I want to add something.

How do you deal with this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

讽刺将军 2024-09-17 03:04:03

你刚刚遇到了空间与时间的问题。我会采用第一种策略,创建一个非常大的图像 10000x10000,原因很简单,你所说的第二种方法涉及大量的矩阵副本,你会不惜一切代价避免这种情况。

此外,在充分了解图像尺寸的情况下,您可以进一步将 10000 x 10000 的值优化为最初的 1000x1000 之类的值。如果图像似乎超过了这个值,请将其加倍,例如 2000 x 2000,然后将旧图像复制到新图像,并在图像扩展时继续执行此操作。这更像是著名的 java 中使用的一种经过验证的策略.util.ArrayList

通过这种方式,您可以间接地弥合时间与空间的权衡。是的,你每次都必须计算边界,但这对我来说并不是一个大任务,它可以在 O(1) 时间内完成。

You've just run into space vs time issue here. I would be going for the first strategy of creating a very large image 10000x10000, the simple reason being the second approach you say involves mountains of matrix copies which you would want to avoid at any cost.

Moreover, with a good knowledge of the image size, you can further optimize that value of 10000 x 10000 to something like 1000x1000 initially. If the image seems to exceed this, double it like 2000 x 2000 and copy the old one to the new one and keep doing this as your image expands.. This is more of a proven strategy that is used in the famous java.util.ArrayList

By this way, you are indirectly bridging the time vs space trade-off. And yes, you will have to calculate the bounds everytime but that does not look a big task to me, it can be done in O(1) time.

梦境 2024-09-17 03:04:03

当然,我们不知道您问题的具体情况,但一个简单的方法可能是这样的:您构建某种图像模型:哪个形状去哪里以及它有多大。由此您应该能够计算出整个图像的尺寸。

Of course we don't know the specifics of your problem but a simple approach could be like this: You build some kind of model of your image: Which shape goes where and how large is it. From that you should be able to calculate the dimensions of the total image.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文