将 InputImage 转换为 Bitmap 的有效方法

May*_*ari 6 android bitmap

我必须使用 Java将com.google.mlkit.vision.common.InputImage转换为 android 中的等效位图图像。现在我正在使用以下代码。

// iImage is an object of InputImage
Bitmap bmap = Bitmap.createBitmap(iImage.getWidth(), iImage.getHeight(), Bitmap.Config.RGB_565);
bmap.copyPixelsFromBuffer(iImage.getByteBuffer());
Run Code Online (Sandbox Code Playgroud)

上面的代码没有将 InputImage 转换为 Bitmap。任何人都可以建议我将 InputImage 转换为 Bitmap 的有效方法。

Ere*_*tik 0

您可以从 byteBuffer 创建位图,可以通过调用方法 getByteBuffer() 接收该位图。在 ML Kit Vision 的官方快速入门示例中,您可以找到如何实现此目的的方法。下面是一段可以解决您的问题的代码:方法 getBitmap() 将 NV21 格式字节缓冲区转换为位图:

@Nullable
  public static Bitmap getBitmap(ByteBuffer data, FrameMetadata metadata) {
    data.rewind();
    byte[] imageInBuffer = new byte[data.limit()];
    data.get(imageInBuffer, 0, imageInBuffer.length);
    try {
      YuvImage image =
          new YuvImage(
              imageInBuffer, ImageFormat.NV21, metadata.getWidth(), metadata.getHeight(), null);
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      image.compressToJpeg(new Rect(0, 0, metadata.getWidth(), metadata.getHeight()), 80, stream);

      Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());

      stream.close();
      return rotateBitmap(bmp, metadata.getRotation(), false, false);
    } catch (Exception e) {
      Log.e("VisionProcessorBase", "Error: " + e.getMessage());
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)

方法旋转位图():

private static Bitmap rotateBitmap(
      Bitmap bitmap, int rotationDegrees, boolean flipX, boolean flipY) {
    Matrix matrix = new Matrix();

    // Rotate the image back to straight.
    matrix.postRotate(rotationDegrees);

    // Mirror the image along the X or Y axis.
    matrix.postScale(flipX ? -1.0f : 1.0f, flipY ? -1.0f : 1.0f);
    Bitmap rotatedBitmap =
        Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

    // Recycle the old bitmap if it has changed.
    if (rotatedBitmap != bitmap) {
      bitmap.recycle();
    }
    return rotatedBitmap;
  }
Run Code Online (Sandbox Code Playgroud)

单击链接可以查看完整代码:https://github.com/googlesamples/mlkit/blob/master/android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/演示/BitmapUtils.java