I’m trying to implement the algorithm used to invert the blue portion of each pixel in a BufferedImage using the BufferedImageOp class, as explained here. My attempt resulted in the creation of this method:
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);*/
}
However, I’m getting errors related to the number of channels or bytes when I call the .filter method of my BufferedImageOp class. The commented sections of code above produce these respective errors:
Error #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)
Error #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)
The code in the link is very old, (it was written in 1998!) so I assume something has changed since then, which is why the code no longer works. However, I haven’t been able to find another source that explains the concept nearly as well, which is a primary concern of mine.
Can anyone explain what these errors mean and how to fix them? Or better yet, point me to a more up-to-date, but still thorough, tutorial on how to manipulate images?
I ran into the same thing… and the answer is to create the destination image with the color model that you are seeking. Also, the short[][] data needs to contain a dimension for the alpha channel as well. Here’s my example of working code that I stumbled upon through trial and error:
This worked for me.