android.media图片转为字节[]

kkl*_*260 1 android google-vision arcore

我正在使用ArSceneView ArFrame获取相机图像

arFragment.getArSceneView().getArFrame().acquireCameraImage()"
Run Code Online (Sandbox Code Playgroud)

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

com.google.api.services.vision.v1.model.Image
Run Code Online (Sandbox Code Playgroud)

我可以告诉我做到这一点的唯一方法是将android.media Image转换为btye [],然后使用byte []创建视觉图像模型。我的问题是我不知道如何转换android.media图像。

kkl*_*260 5

如果有人遇到这个问题。我找到了解决方案:

使用android.media Image模型,我们可以使用以下代码将其转换为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();
}
Run Code Online (Sandbox Code Playgroud)