private boolean needToCreateIndex(RenderedImage image) { SampleModel sampleModel = image.getSampleModel(); ColorModel colorModel = image.getColorModel(); return sampleModel.getNumBands() != 1 || sampleModel.getSampleSize()[0] > 8 || colorModel.getComponentSize()[0] > 8; }
/** Create a color table from the image ColorModel and SampleModel. */ private static byte[] createColorTable(ColorModel colorModel, SampleModel sampleModel) { byte[] colorTable; if (colorModel instanceof IndexColorModel) { IndexColorModel icm = (IndexColorModel) colorModel; int mapSize = icm.getMapSize(); /** * The GIF image format assumes that size of image palette is power of two. We will use * closest larger power of two as size of color table. */ int ctSize = getGifPaletteSize(mapSize); byte[] reds = new byte[ctSize]; byte[] greens = new byte[ctSize]; byte[] blues = new byte[ctSize]; icm.getReds(reds); icm.getGreens(greens); icm.getBlues(blues); /** * fill tail of color component arrays by replica of first color in order to avoid appearance * of extra colors in the color table */ for (int i = mapSize; i < ctSize; i++) { reds[i] = reds[0]; greens[i] = greens[0]; blues[i] = blues[0]; } colorTable = new byte[3 * ctSize]; int idx = 0; for (int i = 0; i < ctSize; i++) { colorTable[idx++] = reds[i]; colorTable[idx++] = greens[i]; colorTable[idx++] = blues[i]; } } else if (sampleModel.getNumBands() == 1) { // create gray-scaled color table for single-banded images int numBits = sampleModel.getSampleSize()[0]; if (numBits > 8) { numBits = 8; } int colorTableLength = 3 * (1 << numBits); colorTable = new byte[colorTableLength]; for (int i = 0; i < colorTableLength; i++) { colorTable[i] = (byte) (i / 3); } } else { // We do not have enough information here // to create well-fit color table for RGB image. colorTable = null; } return colorTable; }