Android.media中的图像转换为byte[]

3
我正在使用 ArSceneView ArFrame 来获取相机图像。
arFragment.getArSceneView().getArFrame().acquireCameraImage()"

这将返回一个 android.media 图像模型。我正在尝试将此图像转换为:

com.google.api.services.vision.v1.model.Image

我唯一能想到的方法是将android.media图像转换为byte[],然后使用该byte[]创建视觉图像模型。我的问题是我无法弄清楚如何转换android.media图像。

1个回答

12

如果有人遇到此问题,我找到了解决方法:

使用android.media图片模型,我们可以使用以下方式将其转换为byte[]-

byte[] data = null;
data = NV21toJPEG(
       YUV_420_888toNV21(image),
            image.getWidth(), image.getHeight());



private static byte[] YUV_420_888toNV21(Image image) {
    byte[] nv21;
    ByteBuffer yBuffer = image.getPlanes()[0].getBuffer();
    ByteBuffer uBuffer = image.getPlanes()[1].getBuffer();
    ByteBuffer vBuffer = image.getPlanes()[2].getBuffer();

    int ySize = yBuffer.remaining();
    int uSize = uBuffer.remaining();
    int vSize = vBuffer.remaining();

    nv21 = new byte[ySize + uSize + vSize];

    //U and V are swapped
    yBuffer.get(nv21, 0, ySize);
    vBuffer.get(nv21, ySize, vSize);
    uBuffer.get(nv21, ySize + vSize, uSize);

    return nv21;
}


private static byte[] NV21toJPEG(byte[] nv21, int width, int height) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    YuvImage yuv = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
    yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
    return out.toByteArray();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接