2012-09-04 45 views
0

我需要對Java的ImageIO API有所幫助。我似乎迷失在ComponentColorModel類中。我需要逐個像素檢查* .png文件來檢測,無論是灰度還是彩色圖像。但是,我不知道如何獲得每個像素的R,G,B值。誰能幫忙?從ComponentColorModel獲取RGB組件

以下代碼將引發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; 
     } 
    } 

回答

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

組件模型定義:

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

這是行不通的。這些方法調用ComponentColorModel中的方法getRGBComponent(int pixel,int idx),並檢查是否存在if(numComponents> 1){0}。 }' 在我的情況下,變量numComponents初始化值爲3.因此,每次調用它時都會得到這個異常... –

1

當你的ImageIO加載圖片時,你應該有一個BufferedImage。 BufferedImage直接提供getRGB(x,y),爲什麼不簡單地使用它並忽略ColorModel?