Search code examples
javaimagergbindexoutofboundsexceptionraster

ArrayIndexOutOfBoundsException when creating an image using Raster


I'm trying to create an image using this array: [-8421505, -8421505, -8421505, -8421505,...] its length is: 62416

BufferedImage img = new BufferedImage(166, 376, BufferedImage.TYPE_INT_RGB);
int pixels[] = new int[166 * 376];

and here is where the error should be

img.getRaster().setPixels(0, 0, 166 , 376, pixels);

then I just save it

File file = new File("new.png");
ImageIO.write(img, "png", file);  

which is:

ArrayIndexOutOfBoundsException : 62416


Solution

  • For some reason, even though it seems like BufferedImage.TYPE_INT_RGB should have 1 int per pixel. When you use WritableRaster#setPixels it actually needs 3 ints per pixel.

    Given some input data,

    int[] values = {...};
    

    Where each int corresponds to a pixel, with 8 bits for RGB respectively. They would need to be put into a bigger array, and unpacked.

    int pixels[] = new int[values.length*3];
    for(int i = 0; i<values.length; i++){
       pixels[3*i] = (values[i]>>16)&0xff;
       pixels[3*i+1] = (values[i]>>8)&0xff;
       pixels[3*i+2] = (values[i])&0xff;
    }
    

    I checked this by creating a values array with red, green and blue.

    int[] values = new int[166*376];
    for(int i = 0; i<166*125; i++){
        values[i] = 0xff0000; //red
    }
    for(int i = 166*125; i<166*250; i++){
        values[i] = 0xff00; //green
    }
    for(int i = 166*250; i<166*376; i++){
        values[i] = 0xff; //blue
    }