3

BufferedImage我正在尝试使用BufferedImageOp该类实现用于反转每个像素的蓝色部分的算法,如此所述。我的尝试导致了这种方法的创建:

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 方法时,我遇到了与通道数或字节数相关的错误。上面代码的注释部分产生了这些相应的错误:

错误 #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:

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)

链接中的代码很旧,(它是在 1998 年编写的!)所以我认为从那时起发生了一些变化,这就是代码不再有效的原因。但是,我还没有找到几乎同样能解释这个概念的另一个来源,这是我最关心的问题。

谁能解释这些错误的含义以及如何解决它们?或者更好的是,给我指出一个关于如何操作图像的更新但仍然全面的教程?

4

1 回答 1

6

我遇到了同样的事情......答案是使用您正在寻找的颜色模型创建目标图像。此外,short[][] 数据还需要包含 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);

这对我有用。

于 2012-11-20T05:07:25.857 回答