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:
Does anyone know why?
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()));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With