}
// build a new palette
IndexColorModel newColorModel = new IndexColorModel(index.getPixelSize(),
index.getMapSize(), reds, greens, blues, alphas);
LookupTableJAI table = buildOpacityLookupTable(0, 1, -1);
ImageLayout layout = new ImageLayout(image);
layout.setColorModel(newColorModel);
RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
result = LookupDescriptor.create(image, table, hints);
} else {
// not indexed, then make sure it's some sort of component color model or turn it into one
RenderedImage expanded;
if (!(colorModel instanceof ComponentColorModel)) {
expanded = new ImageWorker(image).forceComponentColorModel().getRenderedImage();
} else {
expanded = image;
}
// do we have to add the alpha band or it's there and we need to change it?
if (!expanded.getColorModel().hasAlpha()) {
// we just need to add it, so first build a constant image with the same structure
// as the original image
byte alpha = (byte) Math.round(255 * opacity);
ImageLayout layout = new ImageLayout(image.getMinX(), image.getMinY(),
image.getWidth(), image.getHeight());
RenderedOp alphaBand = ConstantDescriptor.create((float) image.getWidth(),
(float) image.getHeight(), new Byte[] { new Byte(alpha) },
new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
result = BandMergeDescriptor.create(expanded, alphaBand, null);
} else {
// we need to transform the existing, we'll use a lookup
final int bands = expanded.getSampleModel().getNumBands();
int alphaBand = bands - 1;
LookupTableJAI table = buildOpacityLookupTable(opacity, bands, alphaBand);
result = LookupDescriptor.create(expanded, table, null);
}
}
image = result;