5

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 = Arrays.stream(imgData)
    .flatMapToInt(Arrays::stream)
    .toArray();

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:

http://i.imgur.com/nkiy2Hv.png

Does anyone know why?

5
  • What's the type of imgData? Two dimensional int[]? Commented Jun 1, 2016 at 15:38
  • 1
    @ManoDestra Yes. It contains int values from 0 to 255 and is exactly of size int[1024][1024]. Commented Jun 1, 2016 at 15:39
  • You create an array called result but then you use source in the function call Commented Jun 1, 2016 at 15:41
  • Ah yes, that's actually a copy error on my part as I was testing to put the original greyscale image into the array, but the result was still the same. very dark...it should be result, i edited that. Commented Jun 1, 2016 at 15:44
  • If you're on Java 8, then you may wish to take a look at the ColorAdjust class. Commented Jun 1, 2016 at 16:16

2 Answers 2

3

I believe you will have better luck using a WritableRaster:

BufferedImage outputImage = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = outputImage.getRaster();
raster.setSamples(0, 0, w, h, 0, result);
ImageIO.write(outputImage, INPUT_FILETYPE, new File(getOutputFileSystemString()));
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.