ARCore 使用 SceneForm 框架 —— Image(通過 acquireCameraImage 獲取)轉 Bitmap

調試工程的時候,提出需要接管 sceneform 框架的視頻數據,說白了就是接管幀數據,也就意味着,處理完幀數據以後,需要手動轉爲可以顯示的圖片資源;網上一大片 ImageView 轉 bitmap 什麼鬼的,已經不是幀數據了,要想從 sceneform 框架中獲取當前攝像頭的幀數據可以通過 frameacquireCameraImage 方法獲取當前幀

    public static Bitmap getBitmapFromImage(Image img) {
        //ImageFormat.YUV_420_888 的 format 數值 35

        ByteBuffer buffer = formatBuffer(img);
        if (buffer == null) {
            return null;
        }

        buffer.rewind();
        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes, 0, bytes.length);

        YuvImage yuvimage = new YuvImage(bytes, ImageFormat.NV21, img.getWidth(), img.getHeight(), null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, img.getWidth(), img.getHeight()), 80, baos);
        byte[] jdata = baos.toByteArray();
        Bitmap bitmapImage = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(bitmapImage != null) {
            return bitmapImage;
        }
        return null;
    }

下面是調用上述的 Image 轉 Bitmap 方法代碼塊,調用上述方法時需要確認 YUV 的格式是否是 ImageFormat.YUV_420_888,對應的 format 數值時 35

    var frame = arFragment!!.arSceneView.arFrame
    var toShow  = frame!!.acquireCameraImage() as ArImage
    var tmpSize = Point(toShow.width, toShow.height)
    var bitmapImage = Utils.getBitmapFromImage(toShow)

Kotlin 和 Java 是支持混編的,再加上最近在學習 Kotlin 所以代碼看起來比較奇怪

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章