0

I have this code to create an ArrayList with all the pixel locations where there is actually a pixel (alpha != 0).

The code is as follows:

public ArrayList<Point> getPixels() {
    ArrayList<Point> output = new ArrayList<Point>();
    Image frameImage = img.getCurrentFrame();
    for (int FIx = 0; FIx <= img.getWidth(); FIx++) {
        for (int FIy = 0; FIy <= img.getHeight(); FIy++) {
            if (frameImage.getColor(FIx, FIy).getAlpha() != 0.00f) {//<-- Error
                output.add(new Point(FIx, FIy));
            }
        }
    }

    return output;
}

The loop can complete fine several times, without any error but on a supposedly random time it is ran, it gives the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 32768
    at org.newdawn.slick.Image.getColor(Image.java:1248)
    at com.SourCherry.games.KittySniper.Enemy.Kitten.getPixels(Kitten.java:197)

I have labelled the line mentioned (Kitten.java:197) with a comment.

If anything else is required to help solve this problem, please ask in the comments. Thanks.

njallam
  • 476
  • 9
  • 23

1 Answers1

2

This looks like the problem to me:

for (int FIx = 0; FIx <= img.getWidth(); FIx++) {
    for (int FIy = 0; FIy <= img.getHeight(); FIy++) {

You're assuming that it's got pixels in a range that includes getWidth and getHeight. I strongly suspect these are exclusive upper bounds:

for (int FIx = 0; FIx < img.getWidth(); FIx++) {
    for (int FIy = 0; FIy < img.getHeight(); FIy++) {

So for example, an image with a width of 3 should have valid X values of 0, 1 and 2 - not 3.

Admittedly this depends on exactly what org.newdawn.slick.Image does, and that's a class I'm not familiar with - but it's a reasonable starting point. (It's a shame that clearly that method doesn't validate its inputs - it should throw a different exception, but it's still your programming error.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @njallam: I don't understand the question... previously your loop bounds were incorrect, hence the exception when `FIy` got to a value which was too high... you've now fixed it, so it doesn't throw. – Jon Skeet Jul 17 '12 at 13:08
  • @njallam: Sounds like it - or possibly the `Image` class in question sometimes allocates an array which is too big, and the fact that it's not validating the parameters means you've been getting away with it - but fetching garbage. – Jon Skeet Jul 17 '12 at 13:47