doc_cropper.dart 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import 'dart:ffi';
  2. import 'package:ffi/ffi.dart';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:native_vision/edge_detection.dart';
  5. import 'package:native_vision/native/dynamic_lib_singleton.dart';
  6. import 'package:path_provider/path_provider.dart';
  7. class DocCropper {
  8. static final bool Function(Pointer<Utf8> imgPath, Pointer<Utf8> outPath,
  9. Pointer<CoordinateArray> coords) _nativeDocCrop =
  10. DynamicLibSingleton()
  11. .dl
  12. .lookup<
  13. NativeFunction<
  14. Bool Function(Pointer<Utf8>, Pointer<Utf8>,
  15. Pointer<CoordinateArray>)>>('native_doc_crop')
  16. .asFunction();
  17. static String? _crop(Map args) {
  18. final tmpDir = args["tmpDir"];
  19. final imgPath = args["imgPath"].toString();
  20. final outPath =
  21. "$tmpDir/cropped_${DateTime.now().millisecondsSinceEpoch}.jpg";
  22. final outPathPtr = outPath.toNativeUtf8();
  23. final imgPathPtr = imgPath.toNativeUtf8();
  24. final succ = _nativeDocCrop(
  25. imgPathPtr, outPathPtr, Pointer.fromAddress(args["coordsArrPtr"]));
  26. malloc.free(imgPathPtr);
  27. malloc.free(outPathPtr);
  28. return succ ? outPath : null;
  29. }
  30. static Future<String?> crop(
  31. String imgPath, EdgeDetectionResult result) async {
  32. final tmpDir = (await getTemporaryDirectory()).path;
  33. final coordsArrPtr = result.toNativeCoords();
  34. final outPath = await compute(_crop, {
  35. "tmpDir": tmpDir,
  36. "imgPath": imgPath,
  37. "coordsArrPtr": coordsArrPtr.address
  38. });
  39. coordsArrPtr.release();
  40. return outPath;
  41. }
  42. }