简体   繁体   中英

Create a bitmap file from random data

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();

There are a couple of APIs that work with images that you may want to look at, including at least one that is part of the standard extension library ( javax.imageio ).

Alternately, if you want to roll this by hand, the BMP file format is not terribly complicated and documentation is easy to find , and sample code is readily available .

Use BufferedImage.setRGB(x, y, rgb) , where rgb is int that you can get by using Color class like Color(data[x][y],data[x][y],data[x][y]).getRGB() . When you end filling pixels just save with ImageIO.write(bufferedImage, "bmp", file) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM