Wayne Rooney
Wayne Rooney

Reputation: 1607

Convert an image to a 2D array and then get the image back in Java

I want to convert an image to a 2D array of pixels, do some operations on it and then convert the resulting 2D array back to image. But I am always getting a pure black image as a result. I cannot figure out where I am going wrong. Here is what I am doing.All operations need to be done on a 8 bit grayscale image.

But I get a complete black image and I am sure that it is not complete black. What should I do to get the correct results?

EDIT - After applying efan's solution, when I save the image to a file, suppose the pixel value of (0,0) is 68 then on computing the pixel value from the same file it changes sometimes to 70 sometimes to 71.. There is small distortion to each pixel.But it spoils the image as a whole. Is there any fix ?

Upvotes: 2

Views: 18370

Answers (1)

efan
efan

Reputation: 968

I think the reason image is completely black is that SampleModel for Raster is wrong. Here is what i did with your code:

private SampleModel sampleModel;

public int[][] compute(File file)
{
    ...
    sampleModel = raster.getSampleModel();
    ...
}

public java.awt.Image getImage(int pixels[][])
{
    ...
    WritableRaster raster= Raster.createWritableRaster(sampleModel, new Point(0,0));
    for(int i=0;i<w;i++)
    {
        for(int j=0;j<h;j++)
        {
            raster.setSample(i,j,0,pixels[i][j]);
        }
    }

    BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY);
    image.setData(raster);
    ...
}

And this worked for me fine. My understanding is that BufferedImage.TYPE_BYTE_GRAY does not select exactly what you need. Something different might work better, but i don't know how exactly those types correspond to color/sample model. And if you know which sample model you need you can just use it:

WritableRaster raster= Raster.createWritableRaster(new PixelInterleavedSampleModel(0, w, h, 1, 1920, new int[] {0}), new Point(0,0));

Upvotes: 5

Related Questions