java - 如何从通过串行端口接收的数据创建 BufferedImage

标签 java bufferedimage javax.imageio

我正在开发一个项目,其中我必须从通过 Xbee 连接到我的计算机的相机 ( cmucam4 ) 获取图像。 问题是我可以通过串口获取图像数据,但是当我将其另存为文件时,该文件无法作为图像打开。 我注意到,当我用notepad++打开文件时,该文件没有像其他图像一样的标题(相机发送bmp图像)。

我尝试使用ImageIO保存图像,但我不知道如何将接收到的数据传递给图像!!

BufferedImage img = new BufferedImage(640, 480,BufferedImage.TYPE_INT_RGB);               
ImageIO.write(img, "BMP", new File("img/tmp.bmp"));

最佳答案

如果相机确实发送BMP格式,则只需将数据写入磁盘即可。然而,更有可能的是(这似乎是这种情况,从您的链接中读取规范),卡发送一个原始位图,这是不一样的。

使用卡规范 PDF 中的此信息:

Raw image dumps over serial or to flash card

  • (640:320:160:80)x(480:240:120:60) image resolution
  • RGB565/YUV655 color space

上面提到的 RGB565 像素布局应该与 BufferedImage.TYPE_USHORT_565_RGB 完美匹配,因此这应该是最容易使用的。

byte[] bytes = ... // read from serial port

ShortBuffer buffer = ByteBuffer.wrap(bytes)
        .order(ByteOrder.BIG_ENDIAN) // Or LITTLE_ENDIAN depending on the spec of the card
        .asShortBuffer();            // Our data will be 16 bit unsigned shorts

// Create an image matching the pixel layout from the card
BufferedImage img = new BufferedImage(640, 480, BufferedImage.TYPE_USHORT_565_RGB);

// Get the pixel data from the image, and copy the data from the card into it
// (the cast here is safe, as we know this will be the case for TYPE_USHORT_565_RGB)
short[] data = ((DataBufferUShort) img.getRaster().getDataBuffer()).getData();
buffer.get(data);

// Finally, write it out as a proper BMP file
ImageIO.write(img, "BMP", new File("temp.bmp"));

PS:上面的代码对我有用,使用长度为 640 * 480 * 2 的 byte 数组,用随机数据初始化(因为我显然没有这样的卡)。

关于java - 如何从通过串行端口接收的数据创建 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882222/

相关文章:

java - 包含表内枚举值的 JCombobox

java - tomcat的域问题

java - 如何在RGB层中隐藏2^12二进制位

java - 从 png PDXObjectImage 获取 BufferedImage

java - 在 JFrame 上绘制 BufferedImage 并写入文件

iphone - ImageIO:CGImageRead_mapData 'open'在应用启动时失败错误= 2

java - 无法初始化类 javax.imageio.ImageIO

Java:mysql查询到JList

java - ImageIO.read( ) 总是旋转我上传的图片

java - varArgs 计算数字总和的示例(独立于输入参数的数量调用相同的方法)