luuksen luuksen - 1 year ago 150
Java Question

Java: save grayscale int array to image

I currently have a simple int[] array of grayscale values from 0 ... 255. I want to save the values to a simple image file. I do the following:

// flatten the 2d array
int[] result =

BufferedImage outputImage = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
outputImage.setRGB(0, 0, w, h, result, 0, w);
ImageIO.write(outputImage, INPUT_FILETYPE, new File(getOutputFileSystemString()));

This actually works fine, but the image is very dark, darker than it should be in my opinion.

Here is the outcoming image in IrfanView. You can actually see details, it's not all black, but it is extremely dark. I set every prixel in the upper left corner to 255, but it still is extremely dark, but you can atleast see the outlines which should in my opinion be white:

Does anyone know why?

Answer Source

You can use the WritableRaster (and forget about getRGB, it's the worst way to access pixels):

int[] myarray = ...
WritableRaster wr = image.getRaster() ;
for (int y=0, nb=0 ; y < image.getHeight() ; y++)
    for (int x=0 ; x < image.getWidth() ; x++, nb++)
        wr.setSample(x, y, 0, myarray[nb]) ;

It's faster to use the DataBuffer, but then you have to handle the image encoding.