我想从原始样本获取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格式,每个像素点占用4个字节(即每个像素点占用1个字节的填充)。图片尺寸为1366x24 px。
根据下面的建议,我终于使代码运行成功了。最终的代码如下:
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)
如果可以改进的话,当然我很乐意听取建议,但总的来说它的表现符合预期。
height
,width
和每个像素的4字节组件数组(RGB顺序+ 1字节填充)或单个int(相同格式)来完成它,我可以解决其余部分。我可能失败的部分是缓冲区<->栅格交互(我甚至不确定两者是否都需要)。非常感谢。 - viraptor