繁体   English   中英

如何将 Bufferedimage 转换为索引类型,然后提取 argb 调色板

[英]How to convert Bufferedimage to indexed type and then extract the argb color palette

我需要将 BufferedImage 转换为 BufferedImage 索引类型以提取颜色数据和 256 调色板的索引。 我认为我正确地将 BufferedImage 转换为索引模式,然后使用下一个代码提取颜色索引:

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();          

我现在的问题是我需要知道每个颜色索引(调色板)的 ARGB 值才能将它们放入数组中。 我一直在阅读有关 ColorModel 和 ColorSpace 的信息,但我没有找到一些方法来完成我需要的工作。

我认为你的代码很好(除了你没有将任何数据“放入”任何东西,你只是引用了数据缓冲区的后备数组,这意味着pixels变化将反映到paletteBufferedImage ,反之亦然)。

要获取以pixels为单位的索引的 ARGB 值:

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)

有关更多信息,请参阅IndexColorModel类文档。

最后我用这个代码解决了它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM