最快的创建方法BufferedImage
从字节数组中TYPE_4BYTE_ABGR
形式,是将数组包装在DataBufferByte
并创建一个交错的WritableRaster
从那。这将确保没有额外的字节数组分配。然后创建BufferedImage
来自光栅和匹配的颜色模型:
public static void main(String[] args) {
int width = 300;
int height = 200;
int samplesPerPixel = 4; // This is the *4BYTE* in TYPE_4BYTE_ABGR
int[] bandOffsets = {3, 2, 1, 0}; // This is the order (ABGR) part in TYPE_4BYTE_ABGR
byte[] abgrPixelData = new byte[width * height * samplesPerPixel];
DataBuffer buffer = new DataBufferByte(abgrPixelData, abgrPixelData.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, samplesPerPixel * width, samplesPerPixel, bandOffsets, null);
ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);
System.out.println("image: " + image); // Should print: image: BufferedImage@<hash>: type = 6 ...
}
但请注意,该图像将是“不受管理的”(某些硬件加速将被禁用),因为您可以直接访问像素阵列。
为了避免这种情况,请创建WritableRaster
没有像素,并将像素复制到其中。这将使用两倍的内存,但会保持图像“受管理”,从而可能获得更好的显示性能:
// Skip creating the data buffer
WritableRaster raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, samplesPerPixel * width, samplesPerPixel, bandOffsets, null);
raster.setDataElements(0, 0, width, height, abgrPixelData);
// ...rest of code as above.
你甚至可以这样做(这可能更熟悉):
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
WritableRaster raster = image.getRaster();
raster.setDataElements(0, 0, width, height, abgrPixelData);