从ComponentColorModel获取RGB组件

时间:2012-09-04 11:44:01

标签: java image-processing

我需要Java的ImageIO API帮助。我似乎在ComponentColorModel类中丢失了。我需要逐个像素地检查* .png文件来检测,无论是灰度还是彩色图像。但是,我无法弄清楚如何获得每个像素的R,G,B值。有人可以帮忙吗?

以下代码抛出IllegalArgumentException,因为它踩到行“m.getComponents(i,components,0);”

ComponentColorModel m = (ComponentColorModel) imageTypeSpecifier.getColorModel();
   int pixels = reader.getWidth(0) * reader.getHeight(0);
   isGray = true;

   int[] components = new int[4];
   for (int i = 0; i < pixels; i++) {
      m.getComponents(i, components, 0);
      if (!(components[0] != components[1] || components[1] != components[2])) {
         isGray = false;
         break;
      }
   }

3 个答案:

答案 0 :(得分:1)

使用ImageIO加载图像时,应该有一个BufferedImage。 BufferedImage直接提供getRGB(x,y),为什么不简单地使用它并忽略ColorModel?

答案 1 :(得分:1)

我自己的解决方案:

BufferedImage buffImage = reader.read(0);
WritableRaster raster = buffImage.getRaster();
int[] colorsInPixel = new int[4];
isColor = false;

// check all pixels one by one
for (int i = 0; i < reader.getWidth(0) * reader.getHeight(0); i++) {
   raster.getPixel(i % reader.getWidth(0), i / reader.getHeight(0), colorsInPixel);
   if (colorsInPixel[0] != colorsInPixel[1] || colorsInPixel[1] != colorsInPixel[2]) {
      isColor = true;
   }
}

答案 2 :(得分:0)

组件模型定义:

public int getRGB(int pixel);
public int getRed(int pixel);
public int getGreen(int pixel);
public int getBlue(int pixel);