2

I have a multidimensional int array that has either a '0' or a '1'. I would like to create an image that resembles a heat map. The elements that have a '0' would be of one color and those of '1' would be of another color. For instance

int [][] test = {{0,0,1}, {1,1,0}, {1,1,1}}

I would get an image of "3 x 3", kind of like this.

wwr
rrw
rrr

where white denotes white and r red.

Thanks for any suggestions.

mre
  • 43,520
  • 33
  • 120
  • 170
Julio Diaz
  • 9,067
  • 19
  • 55
  • 70

3 Answers3

3

The setRGB() or getRaster() methods of BufferedImage work well for this. The examples cited here use SwingWorker, and this example uses a Runnable thread.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Won't that kick your butt performance-wise, since it will abandon acceleration? – mre Jul 07 '11 at 15:36
  • @little: Yes, but I don't think there's enough information in the question to inform a more efficient way to fill the raster. As a practical matter, the example saturates my system at ~50 Hz, but performance degrades gracefully as the events are coalesced. – trashgod Jul 07 '11 at 15:54
1

Seeing as your values are all 1's and 0's, why don't you use a 2-dimensional boolean array? This would save space as well as make the if statements simpler.

You can then use Java's Graphics2D package to draw these dots if you would like to!

This is how I like to set up my Graphics2D instance:

private static BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private static Graphics2D g = image.createGraphics();

Then draw to the image by doing:

g.drawLine(x1, y1, x2, y2);

And save the file by using a method like this one:

private static void saveToFile(){
        try {
            ImageIO.write(image, "png", new File("map.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Ben
  • 11
  • 1
1

Have a look at Java2D.

Basically you want to create a 2d int array for the pixel colors and draw those to an image. Look at the Graphics and Graphics2D objects as well as BufferedImage and the like. Then use Java ImageIO to write the image to a file.

Thomas
  • 87,414
  • 12
  • 119
  • 157