简体   繁体   中英

Using JAI, how do I add a new color to the palette?

I'm using JAI to add a "border" to an image. Eg

ParameterBlock pb = new ParameterBlock();
pb.addSource(r);
pb.add(leftPad);
pb.add(rightPad);
pb.add(topPad);
pb.add(bottomPad);

pb.add(new BorderExtenderConstant(consts));

r = JAI.create("border", pb);

The value of 'consts' above depends on the ColorModel. When using ComponentColorModel each pixel has its own color so I don't have to mess with a palette. When an image has a palette (GIFs, PNGs, ...) the ColorModel is IndexColorModel.

When IndexColorModel is being used then 'consts' is a double[] array, with the size of one. The value in the array is the index in the color palette.

I have found how to modify the palette by creating a new IndexColorModel but the logic I would have to code would be insane! (Eg. How many colors I can have in the palette depends on many factors. Additionally if I need to remove a color from the palette in order to add the new one, I would need logic that determines which color would be best to remove and then modify all pixels previously referencing that color -- wow, that's a lot of code!)

So, my question is, how does one add a color to the palette? Is there an existing library? Or should I be using something from ioimage? (To be honest I'm a little confused where jai "ends" and ioimage "starts".)

Also, side question, for some reason my test images that only have about 10 colors in the palette are read in as having 256 colors. When I then save the image with jai all the 256 colors are saved (11 through 255 are all black). Any idea why it's doing this?

Thanks! David

The best solution I've been able to come up with to my question above is to convert the image from IndexColorModel to ComponentColorModel. (Each pixel of a ComponentColorModel specifies its own color so there is no pallet you have to work with -- you can easily use any color you want.)

I cam up with this simple solution after reading http://java.sun.com/products/java-media/jai/forDevelopers/jaifaq.html#palette

This is what I am doing after reading an image in:

if(image.getColorModel() instanceof IndexColorModel) {
    IndexColorModel icm = (IndexColorModel)image.getColorModel();
    byte[][] data = new byte[4][icm.getMapSize()];

    icm.getReds(data[0]);
    icm.getGreens(data[1]);
    icm.getBlues(data[2]);
    icm.getAlphas(data[3]);

    LookupTableJAI lut = new LookupTableJAI(data);

    image = JAI.create("lookup", image, lut);
}

Once doing the manipulation you can then covert the image back. I haven't spent the time to figure that out. If someone else wants to figure it out you might want to read this: http://www.java.net/node/675577

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM