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?

Anton Kazennikov
  • 3,574
  • 5
  • 30
  • 38

2 Answers2

2

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.

bragboy
  • 34,892
  • 30
  • 114
  • 171
0

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.

musiKk
  • 14,751
  • 4
  • 55
  • 82