(Oracle Java 1.7、Eclipse Kepler、Ubuntu 12.04 64 位)
我需要从ByteBuffer创建一个DataBufferUShort但我所有的尝试在运行时都失败了。
这是怎么做的,赞成?
这是一个失败:( java.lang.UnsupportedOperationException )
ShortBuffer sBuf = imageData.asShortBuffer(); // ByteBuffer
DataBufferUShort dataBufferUShort = new DataBufferUShort(sBuf.array(),
nPixels);
这是堆栈跟踪。第 156 行是上面代码片段中的第二行。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.nio.ShortBuffer.array(ShortBuffer.java:959)
at psw.iu.CreateImage.createGrayscaleImage(CreateImage.java:156)
at psw.iu.TestCreateImage.<init>(TestCreateImage.java:48)
at psw.iu.TestCreateImage.main(TestCreateImage.java:16)
这是创建 ByteBuffer 的方法
public static ByteBuffer createScaledData(WorkingByteBuffer rawWBB,
ByteBuffer scaledByteBuffer) {
rawWBB.byteBuffer.rewind(); // byteBuffer is a ByteBuffer
scaledByteBuffer.rewind();
ShortBuffer inBuf = rawWBB.byteBuffer.asShortBuffer();
ShortBuffer outBuf = scaledByteBuffer.asShortBuffer();
inBuf.rewind();
outBuf.rewind();
int maxDN = MAX_USHORT;
double scaleFactor = (double) maxDN / (double) range;
while (inBuf.hasRemaining()) {
int value = 0xffff & inBuf.get();
int scaledValue = (int) ((double) (value - min) * scaleFactor + 0.5);
if (scaledValue < 0)
scaledValue = 0;
if (scaledValue > maxDN)
scaledValue = maxDN;
outBuf.put((short) scaledValue);
}
return scaledByteBuffer;
}
编辑这没有错误,但这不是我正在寻找的解决方案。
imageData.rewind();
ShortBuffer shortBuffer = imageData.asShortBuffer();
shortBuffer.rewind();
DataBufferUShort dataBufferUShort = new DataBufferUShort( nLines * nPixPerLine);
int index = 0;
while(shortBuffer.hasRemaining()){
dataBufferUShort.setElem(index++, 0xffff & shortBuffer.get());
}