tags:

views:

46

answers:

1
+3  Q: 

Grayscaled image

Hello!

I have still a problem with saving a gray image with Java. How could I do this? The format is not so important, but there should be no image compression.

Does anyone know that?

+3  A: 

This may not be the most elegant method, but it will work:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class ImageTest {


    public static void main(String[] args) throws IOException {

        int width = 10 // width of your image
        int height = 10 // height of your image

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


        for (int x = 0; x < width; ++x)
        {
            for (int y = 0; y < height; ++y)
            {
                int grayscale = ... // get your greyscale value 0..255 from your array here.
                int colorValue = grayscale | grayscale << 8 | grayscale << 16;
                img.setRGB(x, y, colorValue);
            }

        }

        ImageIO.write(img, "png", new File("output.png"));
    }

}

The colorValue is composed of r, g, and b (b on the lowest byte, g one before that, and r one before that). Since your image is greyscale, you can simply use the same r, g and b values for your image, so that's why you can simply do:

int colorValue = grayscale | grayscale << 8 | grayscale << 16;
amarillion
For such kind of rgb manipulation the following notation is much more common (I think it's really easier to understand what's going on 'under the hood'): gray << 16 | gray << 8 | gray
Webinator
Right, good point, that is easier to understand. I've adjusted my example.
amarillion
just one note, if you want Alpha channel, you should use TYPE_INT_ARGB, and shift <<24 for the aloha byte. (i thought this could be useful since you are saving png)
medopal
thanks a lot for you help! it works.
Tim