如何从原始数据创建BufferedImage

我正在尝试从原始样本中获取BufferedImage,但是我尝试读取超出可用数据范围的例外情况,我只是不明白。 我想要做的是:

val datasize = image.width * image.height val imgbytes = image.data.getIntArray(0, datasize) val datamodel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, image.width, image.height, Array(image.red_mask.intValue, image.green_mask.intValue, image.blue_mask.intValue)) val buffer = datamodel.createDataBuffer val raster = Raster.createRaster(datamodel, buffer, new Point(0,0)) datamodel.setPixels(0, 0, image.width, image.height, imgbytes, buffer) val newimage = new BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_RGB) newimage.setData(raster) 

不幸的是我得到:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 32784 at java.awt.image.SinglePixelPackedSampleModel.setPixels(SinglePixelPackedSampleModel.java:689) at screenplayer.Main$.ximage_to_swt(Main.scala:40) at screenplayer.Main$.main(Main.scala:31) at screenplayer.Main.main(Main.scala) 

数据是标准RGB,带有1字节填充(因此1个像素= = 4个字节),图像大小为1366×24像素。


我终于得到了运行以下建议的代码。 最终的代码是:

 val datasize = image.width * image.height val imgbytes = image.data.getIntArray(0, datasize) val raster = Raster.createPackedRaster(DataBuffer.TYPE_INT, image.width, image.height, 3, 8, null) raster.setDataElements(0, 0, image.width, image.height, imgbytes) val newimage = new BufferedImage(image.width, image.height, BufferedImage.TYPE_INT_RGB) newimage.setData(raster) 

如果它可以改进,我当然愿意接受建议,但总的来说它按预期工作。

setPixels假定图像数据打包。 所以它正在寻找一个长度为image.width * image.height * 3的输入,并在数组的末尾运行。

以下是如何解决问题的三个选项。

(1)打开imgbytes ,使其长3倍,并按照与上述相同的方式进行。

(2)从imgbytes手动加载缓冲区而不是使用setPixels

 var i=0 while (i < imgbytes.length) { buffer.setElem(i, imgbytes(i)) i += 1 } 

(3)不要使用createDataBuffer ; 如果您已经知道数据具有正确的格式,则可以自己创建适当的缓冲区(在本例中为DataBufferInt ):

 val buffer = new DataBufferInt(imgbytes, imgbytes.length) 

(如果您的原始副本可能被其他内容变异,您可能需要执行imgbytes.clone )。