我想在java中的BufferedImage上做一个简单的颜色替换。
这是我的代码:
public BufferedImage convertEDEDEDtoRGB(BufferedImage bufferedImage,
short nr, short ng, short nb){
short[] r = new short[256];
short[] g = new short[256];
short[] b = new short[256];
short[] a = new short[256]; //leave a the same
for(short i=0; i<r.length; i++) {
r[i]=i;
g[i]=i;
b[i]=i;
a[i]=i;
}
System.out.println("componentSize "+bufferedImage.getColorModel().getComponentSize());
for(int i = 0; i<bufferedImage.getColorModel().getComponentSize().length; i++)
System.out.println("rgb ("+i+") " +bufferedImage.getColorModel().getComponentSize(i) ); //gives 8 bits
System.out.println("num Components "+bufferedImage.getColorModel().getNumColorComponents()); // gives 3
r[237] = nr;
g[237] = ng;
b[237] = nb;
short[][] ededed2rgb = new short[][]{r, g, b, a};
ShortLookupTable t = new ShortLookupTable(0, ededed2rgb);
LookupOp ededed2rgbOp = new LookupOp(t, null);
bufferedImage = ededed2rgbOp.filter(bufferedImage, null);
return bufferedImage;
}
这会产生以下错误,我只是看不到我在瞎扯:
Number of color/alpha components should be 4 but length of bits array is 2
at java.awt.image.ColorModel.<init>(ColorModel.java:318)
at java.awt.image.ComponentColorModel.<init>(ComponentColorModel.java:256)
at java.awt.image.LookupOp.createCompatibleDestImage(LookupOp.java:396)
at java.awt.image.LookupOp.filter(LookupOp.java:136)
at nl.sytematic.projects.myproj.server.custom.MyServlet.convertEDEDEDtoRGB(GenerateFlavourImageServlet.java:225)
我试过
new short[][] { r,g,b}
但弹出相同的错误。有什么想法吗?顺便提一下,我正在加载一个.png图像(透明度)。
答案 0 :(得分:2)
我将过滤器调用更改为ededed2rgbOb.filter(bufferedImage, bufferedImage)
,错误消失了。通过检查链接上的代码找到了这个。有效地提供第二个参数会绕过createCompatibleDestImage
。
答案 1 :(得分:1)
我想你应该将数组维度化为65536个元素,或者使用ByteLookupTable。