我正在使用 JNA。我正在从我的 C++ 方法中获取原始数据的字节数组。 现在我不知道如何使用这个原始数据字节数组在 Java 中获取缓冲图像。 我尝试了一些方法来将它作为 tiff 图像,但我没有成功。 这是我到目前为止尝试过的代码。 这里我的字节数组包含 16 位灰度图像的数据。我从 x 传感器设备获取此数据。现在我需要从这个字节数组中获取图像。
首先尝试
byte[] byteArray = myVar1.getByteArray(0, 3318000);//array of raw data
ImageInputStream stream1=ImageIO.createImageInputStream(newByteArrayInputStream(byteArray));
ByteArraySeekableStream stream=new ByteArraySeekableStream(byteArray,0,3318000);
BufferedImage bi = ImageIO.read(stream);
第二次尝试
SeekableStream stream = new ByteArraySeekableStream(byteArray);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec = ImageCodec.createImageDecoder(names[0], stream, null);
//at this line get the error ArrayIndexOutOfBoundsException: 0
RenderedImage im = dec.decodeAsRenderedImage();
我想我在这里失踪了。 由于我的数组包含原始数据,因此它不包含 tiff 图像的 header 。 我对吗? 如果是,那么如何在字节数组中提供此 header 。以及最终如何从这个字节数组中获取图像?
为了测试我是否从我的 native 方法中获得了正确的字节数组,我将这个字节数组存储为 .raw 文件,在 ImageJ 软件中打开这个原始文件后,它向我展示了正确的图像,因此我的原始数据是正确的。 我唯一需要的是如何将我的原始字节数组转换为图像字节数组?
最佳答案
这是我用来将原始像素数据转换为 BufferedImage
的方法。我的像素是 16 位签名的:
public static BufferedImage short2Buffered(short[] pixels, int width, int height) throws IllegalArgumentException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
short[] imgData = ((DataBufferShort)image.getRaster().getDataBuffer()).getData();
System.arraycopy(pixels, 0, imgData, 0, pixels.length);
return image;
}
然后我使用 JAI 对生成的图像进行编码。如果您也需要代码,请告诉我。
编辑:感谢@Brent Nash answer,我大大提高了速度关于类似的问题。
编辑:为了完整起见,这里是无符号 8 位的代码:
public static BufferedImage byte2Buffered(byte[] pixels, int width, int height) throws IllegalArgumentException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
byte[] imgData = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
System.arraycopy(pixels, 0, imgData, 0, pixels.length);
return image;
}
关于java - 从原始数据的字节数组中获取缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720212/