coolscitist
coolscitist

Reputation: 3397

Convert values from 0 to 1 to a grayscale image (Java)

I have two dimensional matrix which stores values between 0 to 1. I want to plot these values as levels of gray scale.

If the value is 1, it should be drawn as white. If the value is 0, it should be drawn as black.

How would I do that in java?

I tried the classes: Color and BufferedImage, but I could not figure it out.

Upvotes: 0

Views: 1006

Answers (1)

Greg Kopff
Greg Kopff

Reputation: 16605

To create an image and set the pixels:

final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

for (int y = 0; y < height; y++)
{
  for (int x = 0; x < width; x++)
  {
    image.setRGB(x, y, color);
  }
}

color is an int, in this case, in ARGB format (top byte is alpha, then red byte, green byte, blue byte). Since you're doing greyscale, you want R, G and B to be the same value. You don't want alpha, so you should set that top byte to 0xFF.

See: BufferedImage.setRGB()

Upvotes: 1

Related Questions