我得到这个错误。

线程“主”中的异常java.lang.Error:未解决的编译问题:
rgb2无法解析为变量

它总是导致错误的rgb2数组。如何解决这个问题呢?

    BufferedImage img1 = ImageIO.read(file1);
    BufferedImage img2 = ImageIO.read(file2);

    int w = img1.getWidth();
    int h = img1.getHeight();

    long diff = 0;
    for (int y = 0; y < h; y++) {
      for (int x = 0; x < w; x++) {
        int rgb1[] = img1.getRGB(x, y, w, h, rgb1, 0, w);
        int rgb2[]= img2.getRGB(x, y, w, h, rgb2, 0, w);
        int index = y * w + x;
        int r1 = (rgb1[index] >> 16) & 0xff;
        int g1 = (rgb1[index] >>  8) & 0xff;
        int b1 = (rgb1[index]      ) & 0xff;
        int r2 = (rgb2[index] >> 16) & 0xff;
        int g2 = (rgb2[index]>>  8) & 0xff;
        int b2 = (rgb2[index]     ) & 0xff;
        r2 += Math.abs(r2 - r1);
        g2 += Math.abs(g2 - g1);
        b2 += Math.abs(b2 - b1);

        rgb2[index] = (((r2 & 0xff) << 16) + ((g2 & 0xff) << 8) +(b2 & 0xff));
        rgb2[index] = (rgb2[index]*17);
      }
    }

    int i = 0;
    for (int y = 0; y < h; y++) {
      int red = (y * 255) / (h - 1);
      for (int x = 0; x < w; x++) {
        int green = (x * 255) / (w - 1);
        int blue = 128;
        rgb2[i++] = (red << 16) | (green << 8) | blue;//the problem is at this line
      }
    }
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    image.setRGB(0, 0, w, h, rgb2, 0, w);
    Graphics g = image.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    File imageFile = new File("saved.jpeg");
    ImageIO.write(image, "jpg", imageFile);

}


在循环外声明后,出现此错误。
线程“主”中的异常java.lang.Error:未解决的编译问题:
    局部变量rgb1可能尚未初始化

    int w = img1.getWidth();
    int h = img1.getHeight();
    int scale = w * h * 3;
    int rgb1[] = img1.getRGB(0, 0, w, h, rgb1, 0, w);
    int rgb2[] = img2.getRGB(0, 0, w, h, rgb2, 0, w);

最佳答案

您的问题是因为rgb2[]在此行之前的for循环内声明:

int rgb2[]= img2.getRGB(x, y, w, h, rgb2, 0, w);


然后for循环结束,因此rgb2[]超出范围并从内存中释放,不再定义。如果希望从循环外部访问rgb2[],则必须在调用循环之前先说int rgb2[];,以使变量与需要调用的行在同一范围内。请记住,作用域是向下继承的-在循环内部可以访问循环之前可以访问的任何内容-但不是相反的。

10-08 09:34