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:
- Create a very large image initially, say 10000×10000.
- 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?
You’ve just run into space vs time issue here. I would be going for the first strategy of creating a very large image 10000×10000, 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 1000×1000 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.ArrayListBy 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.