-1

I'm trying to load pixel data into a 2D array. I've already loaded the header, so iData array holds the image data in bytes as a one-dimensional array, but I want it in a two-dimensional array. adjWidth is the width including 00 byte padding.

// get image byteData
byte[] iData = new byte[this.size - 54];
try {
    fin.read(iData);
} catch (IOException ex) {
    System.err.printf("ERROR: File %s is unreadable!\n", filename);
    Logger.getLogger(Bitmap.class.getName()).log(Level.SEVERE, null, ex);
}

// send pixels to the buffer array
// pixels are organized from bottom row to top
this.buffer = new byte[this.height][adjWidth];
for(int i = this.height - 1; i > 0; i--) {
    for(int j = adjWidth - 1; j > 0; j--) {
        this.buffer[i][j] = iData[adjWidth*i + j];
        System.out.print(this.buffer[i][j] + " ");
    }
    System.out.println();
}

However, my output is incorrect when I check it against a hex editor of the file I'm loading. What exactly am I doing wrong?

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48

1 Answers1

-1

Remember that if you are reading byte is different reading integer, in this case one sample or pixel (integer) needs 4 (four) bytes...

CODE EDITED

  BufferedImage BufImgEnt0 = null;
  BufImgEnt0 = ImageIO.read(new File("..."));  // Need Try..Catch

  int OneDArray[] = new int[BufImgEnt0.getWidth()*BufImgEnt0.getHeight()];


  byte bufferR = new byte[BufImgEnt0.getWidth()][BufImgEnt0.getHeight()];
  byte bufferG = new byte[BufImgEnt0.getWidth()][BufImgEnt0.getHeight()];
  byte bufferB = new byte[BufImgEnt0.getWidth()][BufImgEnt0.getHeight()];
  byte bufferA = new byte[BufImgEnt0.getWidth()][BufImgEnt0.getHeight()];

  int RGBA;
  for (int i = 0; i<BufImgEnt0.getWidth();i++){//Begin for i
    for (int j = 0; j<BufImgEnt0.getHeight();j++){//Begin for j
      RGBA = BufImgEnt0.getRGB(i, j);  //Here you have already 2D array

      OneDArray[i*BufImgEnt0.getHeight()+j] = BufImgEnt0.getRGB(i, j); //To One Array 

      bufferR[i][j] = (byte)getR(RGBA);
      bufferG[i][j] = (byte)getG(RGBA);
      bufferB[i][j] = (byte)getB(RGBA);
      bufferA[i][j] = (byte)getAlpha(RGBA);
    }//End for j
  }//End For i


private int getB(int RGB){
  return (RGB>>0)&0xFF;
}
private int getG(int RGB){
  return (RGB>>8)&0xFF;
}
private int getR(int RGB){
  return (RGB>>16)&0xFF;
}
private int getAlpha(int RGB){
  return (RGB>>24)&0xFF;
}

checking your code, the size is heightxWidth x 4 , each pixel needs 4 bytes...

joseluisbz
  • 1,491
  • 1
  • 36
  • 58