9

我正在尝试从原始样本中获取 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 个字节),图像大小为 1366x24 像素。


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

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)

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

4

1 回答 1

10

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;如果您已经知道您的数据具有正确的格式,您可以自己创建适当的缓冲区(在本例中为 a DataBufferInt):

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

imgbytes.clone(如果您的原始副本可能被其他东西变异,您可能需要这样做)。

于 2010-11-21T19:10:52.157 回答