如何从位图中读取图像数据并将其存储在二维数组中?

问题描述:

我想将像素数据加载到二维数组中。我已经加载了头文件,所以iData数组以一维数组的形式保存字节的图像数据,但我希望它在一个二维数组中。 adjWidth是包含00字节填充的宽度。如何从位图中读取图像数据并将其存储在二维数组中?

// 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(); 
} 

但是,当我根据正在加载的文件的十六进制编辑器检查它时,我的输出不正确。我究竟做错了什么?

请记住,如果正在读的字节是不同的阅读整数,此情况下,一个样本或像素(整数)需要4(四)个字节...

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; 
} 

检查你的代码,尺寸是heightxWidth x 4,每个像素需要4个字节...