问题
I'm developing a Java component for displaying some videos and for each frame of the video, my decoder gives me a Color[256] palette + a width*height bytes pixel indices array. Here's how I create my BufferedImage
right now:
byte[] iArray = new byte[width * height * 3];
int j = 0;
for (byte i : this.lastFrameData) {
iArray[j] = (byte) this.currentPalette[i & 0xFF].getRed();
iArray[j + 1] = (byte) this.currentPalette[i & 0xFF].getGreen();
iArray[j + 2] = (byte) this.currentPalette[i & 0xFF].getBlue();
j += 3;
}
DataBufferByte dbb = new DataBufferByte(iArray, iArray.length);
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8 }, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
return new BufferedImage(cm, Raster.createInterleavedRaster(dbb, width, height, width * 3, 3, new int[] { 0, 1, 2 }, null), false, null);
This works but it looks ugly and I'm sure there is a better way. So what would the fastest way to create the BufferedImage
be then?
/Edit: I've tried using the setRGB method directly on my BufferedImage but it resulted in worse performance than the above.
Thanks
回答1:
I would do this:
int[] imagePixels = new int[width * height]
int j = 0;
for (byte i : this.lastFrameData) {
byte r = (byte) this.currentPalette[i & 0xFF].getRed();
byte g = (byte) this.currentPalette[i & 0xFF].getGreen();
byte b = (byte) this.currentPalette[i & 0xFF].getBlue();
imagePixels[j] = 0xFF000000 | (r<<16) | (g<<8) | b;
j++;
}
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
result.setRGB(0, 0, width, height, imagePixels , 0, width);
return result;
Maybe it is faster don't test it yet.
来源:https://stackoverflow.com/questions/23964331/best-way-to-create-image-from-palette-color-array-indice-byte-array