How can I convert a 2 dimensional array of random data to a bitmap? What I am doing is creating a height map using the diamond square algorithm - which works just fine - but I want to be able to visualize the results for testing and debugging purposes. The best way to do this I think is by generating the results as a grayscale bitmap.
I have seen many examples of reading and writing bitmap data (ie reading an image to a bytebuffer and back again) but nothing that would explain how to take random data and create an image with it. All I want to do is take each value of my array and convert it to a grayscale pixel.
For example:
data[0][0] = 98, then pixel (0,0) would be RGB (98,98,98)
data[0][1] = 220, then pixel (0,1) would be RGB (220,220,220)
My random values are already between 0 and 255 inclusive.
Here is one way to do it that's fairly quick. You have to flatten your data into a 1-D array 3 times as long as width*height to use this method. I tested it with a 2D data array populated with Math.random()
in each position
int width = data.length;
int height = data[0].length;
int[] flattenedData = new int[width*height*3];
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int ind = 0;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
greyShade = data[i][j];
flattenedData[ind + j*3] = greyShade;
flattenedData[ind + j*3+1] = greyShade;
flattenedData[ind + j*3+2] = greyShade;
}
ind += height*3;
}
img.getRaster().setPixels(0, 0, 100, 100, flattenedData);
JLabel jLabel = new JLabel(new ImageIcon(img));
JPanel jPanel = new JPanel();
jPanel.add(jLabel);
JFrame r = new JFrame();
r.add(jPanel);
r.show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With