I’m currently working on a simulation with continuous agents, which leave a pheromone trail on a 2d double array. The pheromone trails need to be on a 2d array because of a diffusion with a mean filter that needs to be performed. Ultimately, I need to visualise the agents and the pheromone trails, by transforming the double array directly into an awt.Image
.
Advertisement
Answer
Basically create a BufferedImage
, as suggested by Gilbert Le Blanc and use its setRGB
method to set the pixels (or get its Graphics
to draw on it).
Example, assuming values are between 0.0
and 1.0
, converting to gray:
private static BufferedImage create(double[][] array) { var image = new BufferedImage(array.length, array[0].length, BufferedImage.TYPE_INT_RGB); for (var row = 0; row < array.length; row++) { for (var col = 0; col < array[row].length; col++) { image.setRGB(col, row, doubleToRGB(array[row][col])); } } return image; } private static int doubleToRGB(double d) { var gray = (int) (d * 256); if (gray < 0) gray = 0; if (gray > 255) gray = 255; return 0x010101 * gray; }
The doubleToRGB
can be changed to use more complicated mapping from value to color.
Example red for lower values, blue for higher:
private static int doubleToRGB(double d) { float hue = (float) (d / 1.5); float saturation = 1; float brightness = 1; return Color.HSBtoRGB(hue, saturation, brightness); }
Note: posted code is just to show the idea – can/must be optimized – missing error checking
Note 2: posted mapping to gray is not necessarily the best calculation regarding our perception