import 'dart:ffi'; import 'package:ffi/ffi.dart'; import 'package:flutter/foundation.dart'; import 'package:native_vision/edge_detection.dart'; import 'package:native_vision/native/dynamic_lib_singleton.dart'; import 'package:path_provider/path_provider.dart'; class DocCropper { static final bool Function(Pointer imgPath, Pointer outPath, Pointer coords) _nativeDocCrop = DynamicLibSingleton() .dl .lookup< NativeFunction< Bool Function(Pointer, Pointer, Pointer)>>('native_doc_crop') .asFunction(); static String? _crop(Map args) { final tmpDir = args["tmpDir"]; final imgPath = args["imgPath"].toString(); final outPath = "$tmpDir/cropped_${DateTime.now().millisecondsSinceEpoch}.jpg"; final outPathPtr = outPath.toNativeUtf8(); final imgPathPtr = imgPath.toNativeUtf8(); final succ = _nativeDocCrop( imgPathPtr, outPathPtr, Pointer.fromAddress(args["coordsArrPtr"])); malloc.free(imgPathPtr); malloc.free(outPathPtr); return succ ? outPath : null; } static Future crop( String imgPath, EdgeDetectionResult result) async { final tmpDir = (await getTemporaryDirectory()).path; final coordsArrPtr = result.toNativeCoords(); final outPath = await compute(_crop, { "tmpDir": tmpDir, "imgPath": imgPath, "coordsArrPtr": coordsArrPtr.address }); coordsArrPtr.release(); return outPath; } }