android - 如何将YUV_420_888图像转换为位图

标签 android android-image android-bitmap arcore sceneform

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

最佳答案

这就是我转换为 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;
  }

关于android - 如何将YUV_420_888图像转换为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54017087/

相关文章:

java - 为什么我在运行应用程序时会收到此错误?

android - 任务 ':app:transformClassesAndResourcesWithProguardForProductionRelease' 执行失败

android - 将滤镜效果应用于 Gallery 中的 Android ImageView

android - 错误找不到与给定名称匹配的资源(在 'src' 处,值为 '@drawable/button1')

android - 设置像素;数据类型为 'long' 的像素坐标

android - 如何在Android中隐藏状态栏

android - 无法解析导入 com.google.android.gms

android - 如何在 Android 中使图像成为 Grid View 的背景?

android - 无法从 Google 个人资料图片网址获取位图

java - 自定义 Circlular seek arc 以将位图放置在给定的进度级别