I need to convert a BufferedImage to a BufferedImage indexed type to extract the indices of the colors data and the 256 color palette. i think that i am doing right the conversion of a BufferedImage to indexed mode and then extracting the color indices with the next code:
BufferedImage paletteBufferedImage=new BufferedImage(textureInfoSubFile.getWidth(), textureInfoSubFile.getHeight(),BufferedImage.TYPE_BYTE_INDEXED);
paletteBufferedImage.getGraphics().drawImage(originalBufferedImage, 0, 0, null);
// puts the image pixeldata into the ByteBuffer
byte[] pixels = ((DataBufferByte) paletteBufferedImage.getRaster().getDataBuffer()).getData();
My problem now is that i need to know the ARGB values of each color index( the palette) to put them into an array. i have been reading about ColorModel and ColorSpace but i don´t find some methods to do what i need.
Finally i solve it with this code:
public static BufferedImage rgbaToIndexedBufferedImage(BufferedImage sourceBufferedImage) {
// With this constructor, we create an indexed buffered image with the same dimension and with a default 256 color model
BufferedImage indexedImage = new BufferedImage(sourceBufferedImage.getWidth(), sourceBufferedImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
ColorModel cm = indexedImage.getColorModel();
IndexColorModel icm = (IndexColorModel) cm;
int size = icm.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
icm.getReds(reds);
icm.getGreens(greens);
icm.getBlues(blues);
WritableRaster raster = indexedImage.getRaster();
int pixel = raster.getSample(0, 0, 0);
IndexColorModel icm2 = new IndexColorModel(8, size, reds, greens, blues, pixel);
indexedImage = new BufferedImage(icm2, raster, sourceBufferedImage.isAlphaPremultiplied(), null);
indexedImage.getGraphics().drawImage(sourceBufferedImage, 0, 0, null);
return indexedImage;
}