首页 > 解决方案 > 遍历二维数组

问题描述

嗨,我想遍历每 12 个image像素。如果像素是黑色的,我想把 1 放在我的数组上,否则 0。

int width = image.getWidth();
    int height = image.getHeight();

  
    int[][] pixels = new int[height / 12][width / 12];

    int counterX = 1;
    int counterY = 1;

    for (int i = 0; i < width / 12; i++) {
        for (int j = 0; j < height / 12; j++) {

            if (counterX == 1 && counterY == 1) {
                int rgb = image.getRGB(counterX, counterY);
                String s = Integer.toHexString(rgb);
                if (s.equals("ff000000")) {
                    pixels[i][j] = 1;
                } else {
                    pixels[i][j] = 0;
                }
                counterX += 12;

            } else {

                int rgb = image.getRGB(counterX, counterY);
                String s = Integer.toHexString(rgb);
                if (s.equals("ff000000")) {
                    pixels[i][j] = 1;
                } else {
                    pixels[i][j] = 0;
                }
                counterX += 12;


                if (counterX > width) {
                    counterX = 1;
                    counterY += 12;
                    if (counterY > height) {
                        counterY = height;
                    }
                }
            }
        }
    }
    return pixels;

我的索引 41 超出了长度 41 的范围,它发生在这一行pixels[i][j] = 0; X 有问题。

标签: java

解决方案


推荐阅读