在 java 中将 RAW 图像转换为 jpg

Convert RAW image into jpg in java

我的捕获设备正在返回 RAW 640x480 BGR。支持它的文档只有 .net/C# 个代码示例。

这是他们在 .net SDK 中的示例代码

Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0,
                                                            bmp.Width,
                                                            bmp.Height),
                                              ImageLockMode.WriteOnly,
                                              bmp.PixelFormat);

Marshal.Copy(faceImage, 0, bmpData.Scan0, faceImage.Length);
bmp.UnlockBits(bmpData);

这是我在 Java 中得到的最接近的,但颜色仍然不正确

int nindex = 0;
int npad = (raw.length / nHeight) - nWidth * 3;

BufferedImage bufferedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_4BYTE_ABGR);
DataBufferByte dataBufferByte = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer());
byte[][] bankData = dataBufferByte.getBankData();
byte brgb[] = new byte[(nWidth + npad) * 3 * nHeight];

System.arraycopy(raw, 0, brgb, 0, raw.length);

for(int j = 0; j < nHeight - 1; j++)
{
    for(int i = 0; i < nWidth; i++)
    {
        int base = (j * nWidth + i) * 4;
        bankData[0][base] = (byte) 255;
        bankData[0][base + 1] = brgb[nindex + 1];
        bankData[0][base + 2] = brgb[nindex + 2];
        bankData[0][base + 3] = brgb[nindex];
        nindex += 3;
    }
    nindex += npad;
}

ImageIO.write(bufferedImage, "png", bs);

红色和绿色好像颠倒了。感谢您的反馈以解决此问题。谢谢!

你的代码的以下部分对我来说似乎不太正确

bankData[0][base] = (byte) 255;
bankData[0][base + 1] = brgb[nindex + 1];
bankData[0][base + 2] = brgb[nindex + 2];
bankData[0][base + 3] = brgb[nindex];

您正在使用 TYPE_4BYTE_ABGR 定义缓冲图像。 Java 文档说

The byte data is interleaved in a single byte array in the order A, B, G, R from lower to higher byte addresses within each pixel.

根据您的说法,原始图像的格式也应该是 BGR,因此原始图像中的字节应该从最低字节到最高字节为 B、G、R 的顺序,对吗?据我从您的代码片段中可以看出,您正在将红色通道值复制到绿色通道,将蓝色通道值复制到红色通道,将绿色通道值复制到蓝色通道。复制字节应该是

bankData[0][base] = (byte) 255;
bankData[0][base + 1] = brgb[nindex]; // B
bankData[0][base + 2] = brgb[nindex + 1]; // G
bankData[0][base + 3] = brgb[nindex + 2]; // R