如何读取 .bmp 文件识别 Java 中哪些像素是黑色的

Posted

技术标签:

【中文标题】如何读取 .bmp 文件识别 Java 中哪些像素是黑色的【英文标题】:How to read a .bmp file identify which pixels are black in Java 【发布时间】:2013-06-09 23:51:48 【问题描述】:

类似于以下内容...除了让它工作:

public void seeBMPImage(String BMPFileName) throws IOException 
BufferedImage image = ImageIO.read(getClass().getResource(BMPFileName));

    int[][] array2D = new int[66][66];

for (int xPixel = 0; xPixel < array2D.length; xPixel++)
    
        for (int yPixel = 0; yPixel < array2D[xPixel].length; yPixel++)
        
            int color = image.getRGB(xPixel, yPixel);
            if ((color >> 23) == 1) 
                array2D[xPixel][yPixel] = 1;
             else 
                array2D[xPixel][yPixel] = 1;
            
        
    

【问题讨论】:

那么上面的代码有什么问题呢? 你为什么要测试if((color &gt;&gt; 23) == 1)?这会测试红色分量是否为 128 或更多。 您可以简单地从RGB int 值构造一个Color 对象并直接获取redgreenblue 值... 为什么要在 if-branch 和 else-branch 中分配 1?可能是一个错误...... 【参考方案1】:

我会用这个:

public void seeBMPImage(String BMPFileName) throws IOException 
    BufferedImage image = ImageIO.read(getClass().getResource(BMPFileName));

    int[][] array2D = new int[image.getWidth()][image.getHeight()];

    for (int xPixel = 0; xPixel < image.getWidth(); xPixel++)
        
            for (int yPixel = 0; yPixel < image.getHeight(); yPixel++)
            
                int color = image.getRGB(xPixel, yPixel);
                if (color==Color.BLACK.getRGB()) 
                    array2D[xPixel][yPixel] = 1;
                 else 
                    array2D[xPixel][yPixel] = 0; // ?
                
            
        
    

它向您隐藏了RGB的所有细节,并且更易于理解。

【讨论】:

为什么要自己从原始文件内容中读取位图? ImageIO 为您完成,您可以轻松地使用 BufferedImage 来处理它。抱歉,我对您的问题感到困惑。 你是对的,根据你的解释,我在使用 ImageIO 的道路上是正确的。我将 ImageIO.read(file) 提供给 Raster 以获取原始数据,以便我可以读取每个像素。我想要做的是分别保存每个 BGR 颜色 int 三个不同的 int[] blue、green、red; 数组。但我不知道如何从我从栅格获取的数据中读取此信息【参考方案2】:

mmirwaldt的代码已经在正确的轨道上。

但是,如果您希望数组直观地表示图像:

public void seeBMPImage(String BMPFileName) throws IOException 
    BufferedImage image = ImageIO.read(getClass().getResource(BMPFileName));

    int[][] array2D = new int[image.getHeight()][image.getWidth()]; //*

    for (int xPixel = 0; xPixel < image.getHeight(); xPixel++) //*
    
        for (int yPixel = 0; yPixel < image.getWidth(); yPixel++) //*
        
            int color = image.getRGB(yPixel, xPixel); //*
            if (color==Color.BLACK.getRGB()) 
                array2D[xPixel][yPixel] = 1;
             else 
                array2D[xPixel][yPixel] = 0; // ?
            
        
    

当您使用简单的二维数组循环打印数组时,它会遵循输入图像中的像素位置:

    for (int x = 0; x < array2D.length; x++)
    
        for (int y = 0; y < array2D[x].length; y++)
        
            System.out.print(array2D[x][y]);
        
        System.out.println();
    

注意:修改的行用//*标记。

【讨论】:

以上是关于如何读取 .bmp 文件识别 Java 中哪些像素是黑色的的主要内容,如果未能解决你的问题,请参考以下文章

从 bmp 文件中读取 RGB 像素

C++ - 从 BMP 文件中读取每个像素的位数

Java 读取 bmp 文件?

C语言读取1位的BMP图

如何在c语言 读取BMP图片的信息

用C语言读取16位bmp图片的每个像素的信息~