【问题标题】:Efficient way of converting InputImage to Bitmap将 InputImage 转换为 Bitmap 的有效方法
【发布时间】:2020-08-06 14:28:10
【问题描述】:

我必须使用 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());

以上代码并未将 InputImage 转换为位图。谁能建议我将 InputImage 转换为 Bitmap 的有效方法。

【问题讨论】:

  • 我看到InputImage 有一个方法.getBitmapInternal() 应该返回一个位图,但为我返回null
  • 你解决了这个问题吗?我还需要将 InputImage 转换为 Image
  • @F_Bass,不,先生......

标签: android bitmap


【解决方案1】:

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

@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;
  }

方法rotateBitmap():

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;
  }

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

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 2015-01-05
    • 2013-10-18
    • 2012-06-09
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多