ArrayOutOfBoundException for pixels

Why do I get an ArrayOutOfBoundException for this code?

void setup(){
size(400,400);
}

void draw(){
background(44);
loadPixels();

for(int x=0; x < width; x++){
for(int y=0; y < height; y++){
int index=(x+y*width)*4;
pixels[index]=color(255, 102, 204);
}
}

updatePixels();
}

int index=(x+y*width)*4;

The problem is the * 4 bit !!!

Thanks! You saved my life :slight_smile:

1 Like

Hello,

There is an example and discussion of this (without error) in this tutorial:
Images and Pixels \ Processing.org

Also a discussion of the error (and more) here:

Example using println() to show what happened:

void setup() 
  {
  size(400, 400);
  }

void draw() 
  {
  background(44);
  loadPixels();
  println(pixels.length); //added

  for (int x=0; x < width; x++) 
    {
    for (int y=0; y < height; y++) 
      {
      int index=(x+y*width)*4;
      if (index >= pixels.length-1) println(index,"Woops!"); //added
      pixels[index]=color(255, 102, 204);
      }
    }
  updatePixels();
  }

:)

1 Like