* Force the destination image to be single-banded.
*/
static ImageLayout layoutHelper(ImageLayout layout,
RenderedImage source,
ColorCube colormap) {
ImageLayout il;
if (layout == null) {
il = new ImageLayout(source);
} else {
il = (ImageLayout)layout.clone();
}
// Get the SampleModel.
SampleModel sm = il.getSampleModel(source);
// Ensure an appropriate SampleModel.
if(colormap.getNumBands() == 1 &&
colormap.getNumEntries() == 2 &&
!ImageUtil.isBinary(il.getSampleModel(source))) {
sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
il.getTileWidth(source),
il.getTileHeight(source),
1);
il.setSampleModel(sm);
}
// Make sure that this OpImage is single-banded.
if (sm.getNumBands() != 1) {
// TODO: Force to SHORT or USHORT if FLOAT or DOUBLE?
sm = RasterFactory.createComponentSampleModel(sm,
sm.getTransferType(),
sm.getWidth(),
sm.getHeight(),
1);
il.setSampleModel(sm);
// Clear the ColorModel mask if needed.
ColorModel cm = il.getColorModel(null);
if(cm != null &&
!JDKWorkarounds.areCompatibleDataModels(sm, cm)) {
// Clear the mask bit if incompatible.
il.unsetValid(ImageLayout.COLOR_MODEL_MASK);
}
}
// Set an IndexColorModel on the image if:
// a. none is provided in the layout;
// b. source, destination, and colormap have byte data type;
// c. the colormap has 3 bands; and
// d. the source ColorModel is either null or is non-null
// and has a ColorSpace equal to CS_sRGB.
if((layout == null || !il.isValid(ImageLayout.COLOR_MODEL_MASK)) &&
source.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE &&
il.getSampleModel(null).getDataType() == DataBuffer.TYPE_BYTE &&
colormap.getDataType() == DataBuffer.TYPE_BYTE &&
colormap.getNumBands() == 3) {
ColorModel cm = source.getColorModel();
if(cm == null ||
(cm != null && cm.getColorSpace().isCS_sRGB())) {
int size = colormap.getNumEntries();
byte[][] cmap = new byte[3][256];
for(int i = 0; i < 3; i++) {
byte[] band = cmap[i];
byte[] data = colormap.getByteData(i);
int offset = colormap.getOffset(i);
int end = offset + size;
for(int j = 0; j < offset; j++) {
band[j] = (byte)0;
}
for(int j = offset; j < end; j++) {
band[j] = data[j - offset];
}
for(int j = end; j < 256; j++) {
band[j] = (byte)0xFF;
}
}
il.setColorModel(new IndexColorModel(8, 256,
cmap[0], cmap[1],
cmap[2]));
}
}