2010-11-20 6 views
9

生のサンプルから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) 

データが1つのバイトのパディングを持つ標準のRGBであり、画像サイズ(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) 

それを向上させることができるならば、私はもちろんの提案を開いてんだけど、予想通り、一般的にそれが動作します。

答えて

10

setPixelsは、画像データがではなく、であることを前提としています。したがって、長さimage.width * image.height * 3の入力を探していて、配列の終わりから実行しています。

問題を解決する方法は3つあります。

(1)imgbytesを開梱して3倍長くし、上記と同じ方法で行います。

(2)手動代わりsetPixelsを使用するimgbytesからバッファをロード:

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を行う必要があるかもしれませんelse)。

+0

私はこれらの解決法を試しましたが、無関係のゴミまたは黒い画面が表示されます。私はそれの16進ダンプを見て、データは正しいです。実際にimgbytesからBufferedImageに移動する短いフラグメントを提供できますか?本当に感謝します:) – viraptor

+0

あなたの例で 'イメージ'を生成するコードを提供できるなら、確かに。あるいは、データの仕方に気をつけなければ、私はイメージからではない例を作ります。 –

+0

これは私がXorgから直接得たカスタムオブジェクトです。あなたが知っている 'height'、' width'、そして各ピクセルごとに4バイト成分の配列(RGBオーダー+ 1バイトパディング)、または単一int(同じフォーマット)の配列でそれを行うことができるなら、私は残りを理解することができます。私が失敗する部分はおそらくバッファー<->のラスターインタラクションです(両方とも必要であるかどうかはわかりません)。どうもありがとう。 – viraptor

関連する問題