Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: save grayscale int array to image

Tags:

java

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 = 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?

like image 863
luuksen Avatar asked Jun 01 '16 15:06

luuksen


2 Answers

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()));
like image 113
Johnny Mopp Avatar answered Sep 30 '22 04:09

Johnny Mopp


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.

like image 45
FiReTiTi Avatar answered Sep 30 '22 06:09

FiReTiTi