2012-10-12 120 views
3

我正在試圖使用BufferedImageOp類來實現用於反轉BufferedImage中每個像素的藍色部分的算法,如解釋here所述。我嘗試導致產生這種方法的:BufferedImageOp.filter()投擲通道錯誤

private BufferedImage getInvertedVersion(BufferedImage source) { 
    short[] invert = new short[256]; 
    short[] straight = new short[256]; 
    for (int i = 0; i < 256; i++) { 
     invert[i] = (short)(255 - i); 
     straight[i] = (short)i; 
    } 

    short[][] blueInvert = new short[][] { straight, straight, invert }; //Red stays the same, Green stays the same, Blue is inverted 
    BufferedImageOp blueInvertOp = new LookupOp(new ShortLookupTable(0, blueInvert), null); 

    //This produces error #1 when uncommented 
    /*blueInvertOp.filter(source, source); 
    return source;*/ 

    //This produces error #2 instead when uncommented 
    /*return blueInvertOp.filter(source, null);*/ 
} 

但是,我得到的時候我打電話給我的BufferedImageOp類的.filter方法與渠道或字節數錯誤。上面的代碼中的註釋的部分產生這些相應的錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Number of color/alpha components should be 4 but length of bits array is 2 
at java.awt.image.ColorModel.<init>(ColorModel.java:336) 
at java.awt.image.ComponentColorModel.<init>(ComponentColorModel.java:273) 
at java.awt.image.LookupOp.createCompatibleDestImage(LookupOp.java:413) 

在鏈接代碼非常老,(這是寫:

錯誤#1:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Number of channels in the src (4) does not match number of channels in the destination (2) 
at java.awt.image.LookupOp.filter(LookupOp.java:273) 
at java.awt.image.LookupOp.filter(LookupOp.java:221) 

錯誤#2在1998年!),所以我認爲自那時以來有所改變,這就是爲什麼代碼不再起作用。但是,我一直無法找到解釋這個概念的另一個來源,這是我的主要關注點。

任何人都可以解釋這些錯誤是什麼意思,以及如何解決它們?或者更好的是,將我指向一個更新,但仍然徹底的如何操作圖像的教程?

回答

6

我遇到了同樣的事情...答案是用您正在尋找的顏色模型創建目標圖像。此外,短[] []數據也需要包含alpha通道的維度。這是我通過反覆試驗偶然發現的工作代碼示例:

short[] red = new short[256]; 
short[] green = new short[256]; 
short[] blue = new short[256]; 
short[] alpha = new short[256]; 

for (short i = 0; i < 256; i++) { 
    green[i] = blue[i] = 0; 
    alpha[i] = red[i] = i; 
} 
short[][] data = new short[][] { 
    red, green, blue, alpha 
}; 

LookupTable lookupTable = new ShortLookupTable(0, data); 
LookupOp op = new LookupOp(lookupTable, null); 
BufferedImage destinationImage = new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB); 
destinationImage = op.filter(sourceImage, destinationImage); 

這對我有效。