I have an array called image[][] and i want to create a BufferedImage out of this so I can have the player store it in a file.
1 Answer
// Initialize Color[][] however you were already doing so.
Color[][] image;
// Initialize BufferedImage, assuming Color[][] is already properly populated.
BufferedImage bufferedImage = new BufferedImage(image.length, image[0].length,
BufferedImage.TYPE_INT_RGB);
// Set each pixel of the BufferedImage to the color from the Color[][].
for (int x = 0; x < image.length; x++) {
for (int y = 0; y < image[x].length; y++) {
bufferedImage.setRGB(x, y, image[x][y].getRGB());
}
}
This is a straightforward way of creating (and potentially storing) an image, if that's what you're trying to get at. However, this is not efficient by any means. Try it with a larger image and you'll see a noticeable speed difference.
4 Comments
Andrew Thompson
+1 from before the first edit, but especially for "this is not efficient by any means". It might also be profitable to examine how the
Color array is created in the first place, as it might be much quicker to dispense with the array entirely and draw directly to the image. But that all depends on information that is not known to anyone but the OP.. :(Vineet Kosaraju
Question, what is the difference between BufferedImage.TYPE_INT_RGB and BufferedImage.TYPE_INT_ARGB. I recall using ARGB before, but not RBG. Is the A related with alpha?
Jon Newmuis
@javawarrior I mean... that won't tell us much. But from that, you can tell that this will run
400 * 400 = 160,000 iterations in this loop. If bufferedImage.setRGB(...) is a slow operation, this conversion could be extremely expensive.Jon Newmuis
@Bucco Yes, the A stands for alpha.
BufferedImage.setRGB(x,y,rgb)note it will be slower than some other methods of creating an image from an array. If that does not answer the question (what is the question, BTW?) post an SSCCE of your best attempt.