将.bmp图像加载到2-D字节数组中

时间:2012-10-27 07:17:53

标签: java bitmap byte

我有一个 30 x 40像素.bmp 文件,我要将其加载到inputData中,声明如下:

byte[][] inputData = new byte[30][40];

我对编程比较新,所以任何人都可以告诉我应该使用哪些类来进行编程?谢谢!

我不知道如何访问同一个包中的 .bmp 文件,并将相应的(x, y)位置分配到我的2-D byte array。到目前为止,我有以下内容:

for (int x = 0; x < inputData.length; x++)
{
    for (int y = 0; y < inputData[x].length; y++)
    {
        // inputData[x][y] =
    }
}

2 个答案:

答案 0 :(得分:0)

你知道1个像素是1个字节,但事实并非如此。 RGB像素已经是每像素3个字节。 BMP文件也不是像素阵列而是压缩图像。对阵列的简单加载对您没有帮助。你使用一些现成的库会好得多。

看这里:

GIF http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter06/images.html

BMP http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

TGA http://www.java-tips.org/other-api-tips/jogl/loading-compressed-and-uncompressed-tgas-nehe-tutorial-jogl.html

答案 1 :(得分:0)

您可以使用Java 5+中的ImageIO将BMP文件读入BufferedImageBufferedImage已经可以转换为int[]

在您的情况下,将绿色通道解压缩到字节数组中:

BufferedImage img = ImageIO.read(new File("example.bmp"));
// you should stop here
byte[][] green = new byte[30][40];
for(int x=0; x<30; x++){
  for(int y=0; y<40; y++){
     int color = img.getRGB(x,y);
     //alpha[x][y] = (byte)(color>>24);
     //red[x][y] = (byte)(color>>16);
     green[x][y] = (byte)(color>>8);
     //blue[x][y] = (byte)(color);
  }
}
byte[][] inputData = green;
相关问题