private static BufferedImage applyIndexColourModel(BufferedImage image,
                                                       int width, int height, PColorSpace colourSpace, int bitspercomponent) {
        BufferedImage img;
        colourSpace.init();
        // build out the colour table.
        Color[] colors = ((Indexed) colourSpace).accessColorTable();
        int colorsLength = (colors == null) ? 0 : colors.length;
        int[] cmap = new int[256];
        for (int i = 0; i < colorsLength; i++) {
            cmap[i] = colors[i].getRGB();
        }
        for (int i = colorsLength; i < cmap.length; i++) {
            cmap[i] = 0xFF000000;
        }
        // build a new buffer with indexed colour model.
        DataBuffer db = image.getRaster().getDataBuffer();
        SampleModel sm = new PixelInterleavedSampleModel(db.getDataType(), width, height, 1, width, new int[]{0});
        WritableRaster wr = Raster.createWritableRaster(sm, db, new Point(0, 0));
        ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, false, -1, db.getDataType());
        img = new BufferedImage(cm, wr, false, null);
        return img;
    }