IndexColorModel

Hello,
I have a gif image that i load with ImageIO. It has 3 colors + transparent background(saved with gimp, indexed mode, 3 colors). I want to be able to use several different paletes for this image, infact i want to create another bufferedimage, with new palete and draw the old one on it.


int[] cmap = { 0xff2e00a4, 0xff2401d6, 0xff6c4eee, 0x00000000};
IndexColorModel icm = new IndexColorModel(8, cmap.length, cmap, 0,true,3,DataBuffer.TYPE_BYTE);

BufferedImage image = new BufferedImage(20,25,BufferedImage.TYPE_BYTE_INDEXED,icm);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
g2d.fillRect(0, 0, 20, 25);

The problem is that when i draw the original image on it, only one color is visible, ant the two others seem to be transparent.

The code:


IndexColorModel cm = (IndexColorModel)originalImage.getColorModel();		
System.out.println(cm.getMapSize());
System.out.println(cm.getTransparentPixel());

Prints 4,3.
Any ideas?

It seems as though you are trying to perform a palette swap?

If so, drawing the image from the 1st image onto the 2nd is not the correct approach.
When drawing onto an Image with an IndexColorModel it isn’t just a case of copying the source raster onto the destination raster, the source colors must be mapped onto the closest color in the destination palette.

Obviously if the palettes of your 2 BufferedImages are dissimilar this process will not result in the outcome you want. (The mapping process can also be very slow)

What you should do is construct the 2nd BufferedImage using the Raster of your 1st BufferedImage (bi1.getRaster()), but providing a different (new) ColorModel.
The constructor you will be wanting is:

BufferedImage(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable<?,?> properties) 

I’m unsure if a copy of the provided raster is taken, you might find that the 2 images end up sharing the same Raster… which might or might not be desirable, depending upon what you intend to do with the images.
You can ofcourse clone the Raster if sharing is not desirable.

Thank you! The problem is solved now.