1

I created 2D array of floats in java, representing gray scale image, when each pixel is normalized - it between [0,1].

How can I take the 2D array and display the image (in gray scale of course)?

ty!

user8446864
  • 105
  • 1
  • 9
  • That depends on how you plan to display an image, are you trying to write it to a file or display it on screen directly (using something like Swing)? – phflack Dec 06 '17 at 15:58
  • It doesn't meter. I prefer to display in on the screen. – user8446864 Dec 06 '17 at 15:59
  • Take a look at [Convert an array of floats into an image](https://stackoverflow.com/q/7758139/5475891) and [How to save a BufferedImage as a File](https://stackoverflow.com/a/12674109/5475891) – phflack Dec 06 '17 at 16:02

1 Answers1

2

The easiest way is to make a BufferedImage out of it. To do that, you'll have to convert the values into colors:

int toRGB(float value) {
    int part = Math.round(value * 255);
    return part * 0x10101;
}

That first converts the 0-1 range into 0-255 range, then produces a color where all three channels (RGB - red, green and blue) have the same value, which makes a gray.

Then, to make the whole image, set all the pixel values:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
        image.setRGB(x, y, toRGB(theFloats[y][x]));

Once you have the image, you can save it to a file:

ImageIO.save(image, 'png', new File('some/path/file.png'));

Or, display it in some way, perhaps with Swing.. See for example this question.

xs0
  • 2,990
  • 17
  • 25