【问题标题】:How to convert YUV_420_888 image to bitmap [duplicate]如何将YUV_420_888图像转换为位图[重复]
【发布时间】:2019-05-29 17:39:12
【问题描述】:

我正在从事 AR 项目,我需要捕获当前帧并将其保存到图库。我可以使用 AR 核心中的 Frame 类获取图像,但图像的格式是 YUV_420_888。我已经尝试了很多解决方案来将其转换为位图,但无法解决。

【问题讨论】:

    标签: android android-image android-bitmap arcore sceneform


    【解决方案1】:

    这就是我转换为 jpeg 的方式。

    public Bitmap imageToBitmap(Image image, float rotationDegrees) {
    
        assert (image.getFormat() == ImageFormat.NV21);
    
        // NV21 is a plane of 8 bit Y values followed by interleaved  Cb Cr
        ByteBuffer ib = ByteBuffer.allocate(image.getHeight() * image.getWidth() * 2);
    
        ByteBuffer y = image.getPlanes()[0].getBuffer();
        ByteBuffer cr = image.getPlanes()[1].getBuffer();
        ByteBuffer cb = image.getPlanes()[2].getBuffer();
        ib.put(y);
        ib.put(cb);
        ib.put(cr);
    
        YuvImage yuvImage = new YuvImage(ib.array(),
                ImageFormat.NV21, image.getWidth(), image.getHeight(), null);
    
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        yuvImage.compressToJpeg(new Rect(0, 0,
                image.getWidth(), image.getHeight()), 50, out);
        byte[] imageBytes = out.toByteArray();
        Bitmap bm = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        Bitmap bitmap = bm;
    
        // On android the camera rotation and the screen rotation
        // are off by 90 degrees, so if you are capturing an image
        // in "portrait" orientation, you'll need to rotate the image.
        if (rotationDegrees != 0) {
          Matrix matrix = new Matrix();
          matrix.postRotate(rotationDegrees);
          Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm,
                  bm.getWidth(), bm.getHeight(), true);
          bitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                  scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        }
        return bitmap;
      }
    

    【讨论】:

    • 您说“后跟交错的 Cb Cr”,但实际上您并没有交错它们?看来你只是一个接一个地复制,和交错不一样
    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2016-08-16
    • 2012-03-11
    • 2014-01-26
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多