import 'dart:ui';

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:google_mlkit_object_detection/google_mlkit_object_detection.dart';

/// 图片预处理
/// [camera] 相机
/// [image] 图片
/// [onImage] 回调函数
Future<InputImage?> processCameraImage(
  CameraDescription camera,
  CameraImage image,
  void Function(InputImage inputImage) onImage,
) async {
  final WriteBuffer allBytes = WriteBuffer();
  for (final Plane plane in image.planes) allBytes.putUint8List(plane.bytes);
  final bytes = allBytes.done().buffer.asUint8List();
  final Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
  final imageRotation = InputImageRotationValue.fromRawValue(camera.sensorOrientation);
  if (imageRotation == null) return null;
  final inputImageFormat = InputImageFormatValue.fromRawValue(image.format.raw);
  if (inputImageFormat == null) return null;
  final planeData = image.planes
      .map((Plane plane) => InputImagePlaneMetadata(
            bytesPerRow: plane.bytesPerRow,
            height: plane.height,
            width: plane.width,
          ))
      .toList();
  final inputImageData = InputImageData(
    size: imageSize,
    imageRotation: imageRotation,
    inputImageFormat: inputImageFormat,
    planeData: planeData,
  );
  final inputImage = InputImage.fromBytes(bytes: bytes, inputImageData: inputImageData);
  onImage(inputImage);
}