我有一个包含 BGRA 栅格数据的 byte[] 数组(例如,第一个字节 = 蓝色分量,第二个 = 绿色,第五个 = 下一个像素,蓝色),我想使用它。
具体来说,是否有一个 Java 类已经被设计来包装这样的东西?我想知道,因为我想让我的代码尽可能整洁/正确,如果 Java 已经有一个更快的编译版本,那么我会选择它。
更具体地说,我想将 byte[] 数组转换为 2 个数组,其中 BGR1[] + BGR2[] = BGR,A1 = A2 = A。
我当然可以为此编写原始代码,但也许有一种更整洁/更快的方法。
这是否很快,但它肯定更有用。我的源数据数组来自 Kinect 的 Color Stream,使用 J4KSDK。
我使用这种方法的目标是读取图像的二进制字节。我相信您可以根据自己的用途对其进行修改。
/* Reference imports */
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/* method */
public byte[] getImage(byte[] bytes) throws IOException {
int width = 640;
int height = 480;
int[] shifted = new int[width * height];
// (byte) bgra to rgb (int)
for (int i = 0, j = 0; i < bytes.length; i = i + 4, j++) {
int b, g, r;
b = bytes[i] & 0xFF;
g = bytes[i + 1] & 0xFF;
r = bytes[i + 2] & 0xFF;
shifted[j] = (r << 16) | (g << 8) | b;
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedImage.getRaster().setDataElements(0, 0, width, height, shifted);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "JPG", baos);
byte[] ret = baos.toByteArray();
return ret;
}
您可以看到另一个问题,它对良好的Java图像处理库有响应。