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 の入力を探し、配列の最後まで実行します。

問題を解決するための 3 つのオプションを次に示します。

imgbytes(1) 3倍の長さになるように開梱し、上記と同様に行う。

imgbytes(2)を使用する代わりに、手動でバッファーをロードし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 に答える