简体   繁体   English

将RGB数据的byte []转换为图像

[英]Convert byte[] of RGB data to a image

I have a byte[] I captured from Kinect using OpenKinect and it's Java JNA wrapper. 我有一个使用OpenKinect从Kinect中捕获的byte [],它是Java JNA包装器。 I'm wondering if there's any existing library I can use to convert the byte[] of RGB data into a image I can display/store? 我想知道是否可以使用现有的库将RGB数据的byte []转换为可以显示/存储的图像?

Java's BufferedImage is a great candidate . Java的BufferedImage是一个不错的选择

I would find out the color encoding scheme of your byte[] and transform it to an int[] acceptable for setting the RGB array of a BufferedImage with setRGB() javadoc . 我会找出您的byte[]的颜色编码方案,并将其转换为可以使用setRGB() javadoc设置BufferedImage的RGB数组的int[] Then you can save the image to disk in a variety of formats, or render for display. 然后,您可以将图像以各种格式保存到磁盘,或渲染以显示。

You can convert the byte[] RGB data into an int[] where each int encodes an ARGB pixel (alpha, red, green, blue). 您可以将byte[] RGB数据转换为int[] ,其中每个int会编码ARGB像素(alpha,红色,绿色,蓝色)。 Then use the following code to create a BufferedImage 然后使用以下代码创建一个BufferedImage

int[] pixels = new int[width * height];
// do the conversion byte[] => int[]
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
img.setRGB(0, 0, width, height, pixels, 0, width);

You can then use ImageIO to save the image: 然后可以使用ImageIO保存图像:

File outputFile = new File("image.png");
ImageIO.write(img, "png", outputFile);

Or draw the image for example in a JComponent's paint method: 或例如使用JComponent的paint方法绘制图像:

public void paint(Graphics graphics){
  Graphics2D g = (Graphics2D)graphics;
  g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
}

Consult the related JavaDoc for details. 有关详细信息,请查阅相关的JavaDoc。 BufferedImage.TYPE_INT_ARGB is usually the fastest image encoding (at least it was a while ago on Mac OS X and Windows) even if you don't use any alpha at all. BufferedImage.TYPE_INT_ARGB通常是最快的图像编码(至少在一段时间之前在Mac OS X和Windows上是这样),即使您根本不使用任何Alpha。

Disclaimer: Code examples have not been tested. 免责声明:代码示例未经测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM