所有的,
我在scala中利用bufferedimages和光栅对象进行一些图像处理。我试图用以下代码获取缓冲图像中的所有像素。
val raster = f.getRaster()
// Preallocating the array causes ArrayIndexOutOfBoundsException .. http://forums.sun.com/thread.jspa?threadID=5297789
// RGB channels;
val pixelBuffer = new Array[Int](width*height*3)
val pixels = raster.getPixels(0,0,width,height,pixelBuffer)
现在,当我读取相对较大的文件时,这很好。当我读取20x20 PNG文件时,我得到一个arrayindexoutofboundsException:
java.lang.ArrayIndexOutOfBoundsException: 1200
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1050)
我读过
online
解决这个问题的方法不是预先分配PixelBuffer,而是传递一个空值,并使用由graster.getPixels方法返回的值。
这是我的问题。当我采用幼稚的方法,把零作为最后一个论点:
val pixels = raster.getPixels(0,0,width,height,Nil)
我得到错误
error: overloaded method value getPixels with alternatives (Int,Int,Int,Int,Array[Double])Array[Double] <and> (Int,Int,Int,Int,Array[Float])Array[Float] <and> (Int,Int,Int,Int,Array[Int])Array[Int] cannot be applied to (Int,Int,Int,Int,Nil.type)
val pixels = raster.getPixels(0,0,width,height,Nil)
很明显,编译器无法确定我要调用的两个方法中的哪一个;这是不明确的。如果我使用Java,我将抛出NULL使我的意图明确。我不太明白如何在scala中获得同样的效果。我尝试过的事情:
val pixelBuffer:Array[Int] = Nil // Cannot instantiate an Array to Nil for some reason
Nil.asInstanceOf(Array[Int]) // asInstanceOf is not a member of Nil
你知道如何明确地告诉编译器我想要用int数组作为最后一个参数而不是浮点数组的方法吗?
编辑:
正如一个答案指出的那样,我得到的是零和零。nil是一个空列表。请参阅以下内容
blog post
另外,我应该指出数组越界异常是我的错(正如这些事情经常发生的那样)。问题是我假设光栅有3个通道,但我的图像有4个通道,因为我是这样创建的。我改为按如下方式预分配阵列:
val numChannels = raster.getNumBands()
val pixelBuffer = new Array[Int](width*height*numChannels)
val pixels = raster.getPixels(minX,minY,width,height,pixelBuffer)
谢谢你的帮助