Question

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.

Was it helpful?

Solution 2

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;
}

OTHER TIPS

I think your code is good (except that you don't "put" any data into anything, you merely reference the data buffer's backing array, meaning changes in pixels will reflect to paletteBufferedImage and vice versa).

To get the ARGB values for the indices in pixels:

IndexColorModel indexedCM = (IndexColorModel) paletteBufferedImage.getColorModel(); // cast is safe for TYPE_BYTE_INDEXED
int[] palette = new int[indexedCM.getMapSize()]; // Allocate array
indexedCM.getRGBs(palette); // Copy palette to array (ARGB values)

For more information, see the IndexColorModel class documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top