2

I have a color image of MxN, in row x column format. I want to store all the red components of the image in a separate matrix, all the green component in a separate matrix and all the blue component in a separate matrix. Perform transformation on all the three matrix and generate back the shuffled RGB image. I am able to store it in single matrix using the below code, but unable to store it in three separate matrices.

double[][] img = new double[bi.getHeight()][bi.getWidth()];

img[i][j] = bi.getRGB(i, j);

1 Answers1

1

As of Understanding BufferedImage.getRGB output values, you have several possibilities:

You need to initialize the arrays:

int[][] blue = new int[bi.getHeight()][bi.getWidth()];
int[][] green = new int[bi.getHeight()][bi.getWidth()]; 
int[][] red = new int[bi.getHeight()][bi.getWidth()]; 
int[][] alpha = new int[bi.getHeight()][bi.getWidth()]; 

1) simplest to understand, bit more overhead: use Color

Color mycolor = new Color(img.getRGB(x, y));
red[x][y] = mycolor.getRed();
blue[x][y] = mycolor.getBlue();
green[x][y] = mycolor.getGreen();

2) do those computations by hand

int color = bi.getRGB(x, y);

// Components will be in the range of 0..255:
blue[x][y] = color & 0xff;
green[x][y] = (color & 0xff00) >> 8;
red[x][y] = (color & 0xff0000) >> 16;
alpha[x][y] = (color & 0xff000000) >>> 24;

3) print as a String and extract the values again (this is more of theoretical value, do not use this without knowing what you do)

print the value as an unsigned 32bit hex value:

String s = Integer.toString(bi.getRGB(x,y), 16)
blue[x][y] = Integer.parseInt(s.substring(24, 32), 2);
green[x][y] = Integer.parseInt(s.substring(16, 24), 2);
red[x][y] = Integer.parseInt(s.substring(8, 16), 2);
alpha[x][y] = Integer.parseInt(s.substring(0, 8), 2);

Each two characters of the output will be one part of the ARGB set.

4) use ColorModel (it is unclear whether it can be done)

It has getAlpha, getRed, etc methods, but the pixels are a single 1-D array. If someone knows how to use it, feel free.

Community
  • 1
  • 1
serv-inc
  • 35,772
  • 9
  • 166
  • 188