2

I have an int[image.height][image.width] array of the image. Now I'm trying to turn it back to image file but I've failed.

This is what I have done:

private void intToImg(int[][] pxls,String path){
    BufferedImage image = new BufferedImage(pxls[0].length, pxls.length, BufferedImage.TYPE_INT_ARGB);
    WritableRaster raster = (WritableRaster)image.getData();
    int[] pxlsr=new int[pxls[0].length*pxls.length];
    int k=0;
    for(int i=0;i<pxls.length;i++)for(int j=0;j<pxls[0].length;j++)pxlsr[k++]=pxls[i][j];
    raster.setPixels(0,0,pxls[0].length-10,pxls.length-10,pxlsr);//index out of bounds error here...
    File f = new File(path);
    try{ImageIO.write(image, "JPG", f);}
    catch (IOException x){x.printStackTrace();}
}

However I always have the same error java.lang.ArrayIndexOutOfBoundsException. What did I do wrong and what is the right way to transform array of pixels into real image?

I've just increased array length in 4 and java.lang.ArrayIndexOutOfBoundsException has finally disapeared. But I'm still can't create real image. Instead I have image filled with #000009 no matter what value of array.

This is what i was doing:

for(int i=0;i<pxls.length;i++)for(int j=0;j<pxls[0].length;j++){
        pxlsr[k++]=pxls[i][j];
        pxlsr[k++]=pxls[i][j];
        pxlsr[k++]=pxls[i][j];
        pxlsr[k++]=pxls[i][j];
    }
raster.setPixels(0,0,pxls[0].length,pxls.length,pxlsr);

and

for(int i=0;i<pxls.length;i++)for(int j=0;j<pxls[0].length;j++){
        pxlsr[k++]=111;
        pxlsr[k++]=111;
        pxlsr[k++]=111;
        pxlsr[k++]=111;
    }
raster.setPixels(0,0,pxls[0].length,pxls.length,pxlsr);

and many other thing but the result is allways the same - image filled with black color!

0

3 Answers 3

2

finally i did it! i found error!

instead of:

WritableRaster raster = (WritableRaster)image.getData();

should be:

WritableRaster raster = image.getRaster();
Sign up to request clarification or add additional context in comments.

Comments

1

You can write your bytes directly by calling

image.setRGB(0, 0, pxls[0].length, pxls.length, pxlsr, 0, pxls[0].length);

That works for me.

1 Comment

as i understand it, image.setRGB is fine, but it tends to be really slow. This is why people are trying to use the raster instead
0

A classic error with images is confusion about what width and height represent in terms of rows and columns in the array. A BufferedImage must be of size width x height, which might correspond to pxls[0].length x pxls[length] and not the contrary.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.