BufferedImage and TYPE_BYTE_GRAY

Folks,
I’m loading an 8-bit grayscale image (RAW) into a one dimensional array representing pixels.
Knowing the width and height of the image I’m using BufferedImage to create an Image object and then paint this onto the screen.
(code below)

The problem is that the loaded image (being 8bit) contains 255 colors yet the displayed image has only 19 colors:

What it should look like:

http://vault101.co.uk/downloads/good.jpg

How it is displayed:

http://vault101.co.uk/downloads/bad.jpg


Image image;

   // snippet
        int width = 513;
        int height = 513;
        byte[] b = null;
        int[] pixels = new int [(width*height)];
        b = generatePixels (width, height);
        
        for (int i=0; i < b.length; i++)
        {
            pixels[i] = b[i] & 0xFF;
        }

        BufferedImage recoverImg = new BufferedImage (width,height,BufferedImage.TYPE_BYTE_GRAY);
        myImg.setRGB (0,0,width,height,pixels,0,width);
        image = myImg.getScaledInstance (width, height, Image.SCALE_SMOOTH);
        
        Frame frame = new Frame ("Test");
        frame.add (this);
        frame.setSize (600, 600);
        frame.setVisible (true);
        this.repaint ();

I don’t have a problem with the RAW loader - outputting the values of the array shows all colours from 0 to 255 are present. It’s the displaying that seems to be the issue. Any ideas?

I think this is your problem. Is there a reason you need to use getScaledInstance?
You don’t change the size of the image.

Thanks,
Dmitri
Java2D Team

myImg.setRGB (0,0,width,height,pixels,0,width);

There is the problem. See api doc.

“Sets an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, into a portion of the image data. Color conversion takes place if the default model does not match the image ColorModel.”

That explains why the luminance is only a third of what it should be.

You could either do some bit op voodoo… or you could try MemoryImageSource… or WritableRaster…

I think oNyx is correct. You need to set the pixels to the raster to avoid color conversion:
instead of Img.setRGB use


Img.getRaster().setPixels(0, 0, width, height, pixels);

Thanks,
Dmitri

Thanks for the assistance guys! Using .getRaster().setPixels (…) seems to have fixed the problem.

Pete