assign RGB values in java with nested for function

170 views Asked by At

I have some question, here is my code :

int W = img.getWidth();
int H = img.getHeight();
int [][] pixels = new int [W][H];
int [][][] rgb = new int [3][H][W];
for(int i=0;i<W;i++)
    for(int j=0;j<H;j++){
        pixels[i][j] = img.getRGB(i,j);
        Color clr = new Color(pixels[i][j]);
        rgb[0][j][i] = clr.getRed();
        rgb[1][j][i] = clr.getGreen();
        rgb[2][j][i] = clr.getBlue();
    }

/*
 pixels changing process 
 */

//1st for
for(int[] asd : rgb[0])
    System.out.println(Arrays.toString(asd));

//2nd for
for(int i=0;i<W;i++)
    for(int j=0;j<H;j++){
        /*Color myColor = new Color (rgb[0][i][j],rgb[1][i][j],rgb[2][i][j]);
        int newrgb = myColor.getRGB();
        img.setRGB(W,H,newrgb);*/
    }
}

printing the red values with 1st works normally, but why I can't put that values using 2nd for ?

when I run the code, it issues ByteInterleavedRaster.setDataElements(int, int, Object) line: not available

I want to assign image colors with new values of rgb[0] (red), rgb[1] (green), rgb[2] (blue) that printed by using 1st for. When I expected it could work with 2nd for, it threw an error.

thanks in advance :)

2

There are 2 answers

4
libik On BEST ANSWER

You have to change this line img.setRGB(W,H,newrgb) to this one img.setRGB(j,i,newrgb).

3
VILLAIN bryan On

I think this looks correct

int W = img.getWidth();
int H = img.getHeight();
int [][]   pixels = new int [W][H];
int [][][] rgb    = new int [3][W][H];

for(int i=0; i<W; i++)
    for(int j=0; j<H; j++) {

        pixels[i][j] = img.getRGB(i,j);
        Color clr = new Color(pixels[i][j]);

        rgb[0][i][j] = clr.getRed();
        rgb[1][i][j] = clr.getGreen();
        rgb[2][i][j] = clr.getBlue();
    }

/*
 pixels changing process 
 */

for(int i=0; i<W; i++)
    for(int j=0; j<H; j++){

        Color myColor = new Color (rgb[0][i][j],
                                   rgb[1][i][j],
                                   rgb[2][i][j]);
        int newrgb = myColor.getRGB();

        img.setRGB(i, j, newrgb);
    }
}