所有,
我正在使用BufferedImages和Raster对象在Scala中进行一些图像处理.我试图使用以下代码获取缓冲图像中的所有像素.
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,width,height,pixelBuffer)
现在,当我读取相对较大的文件时,这很好用.当我读入20×20 PNG文件时,我得到一个ArrayIndexOutOfBoundsException:
java.lang.ArrayIndexOutOfBoundsException: 1200
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1050)
我已经阅读了online,解决这个问题的方法是不预先分配pixelBuffer,而是传入一个空值并使用Raster.getPixels方法返回的值.
这是我的问题.当我做天真的方法,并将Nil作为最后一个参数传递:
val pixels = raster.getPixels(0,Nil)
我收到了错误
error: overloaded method value getPixels with alternatives (Int,Int,Array[Double])Array[Double] (Int,Array[Float])Array[Float] (Int,Array[Int])Array[Int] cannot be applied to (Int,Nil.type)
val pixels = raster.getPixels(0,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数组作为最后一个参数而不是Float数组的方法?
编辑:
正如一个答案所指出的那样,我让Nil与null混淆了. Nil是一个空列表.请参阅以下blog post
另外,我应该指出数组越界异常是我的错(因为这些事情经常是这样).问题是我假设光栅有3个通道,但我的图像有4个通道,因为我已经创建了它.我改为预先分配数组如下:
val numChannels = raster.getNumBands()
val pixelBuffer = new Array[Int](width*height*numChannels)
val pixels = raster.getPixels(minX,minY,pixelBuffer)
谢谢您的帮助