ocr_plugin_flutter 1.0.0 copy "ocr_plugin_flutter: ^1.0.0" to clipboard
ocr_plugin_flutter: ^1.0.0 copied to clipboard

ocr_plugin_flutter project.

身份证OCR #

身份证采集

平台支持(兼容性) #

Android iOS
适用版本区间:4.4以上 适用版本区间:9 - 14

环境准备 #

CocoaPods 安装教程

资源引入/集成 #

在 pubspec.yaml 中添加

dependencies:
    ocr_plugin_flutter: ^1.0.0

项目开发配置 #

Android 配置

插件依赖于相机权限,需要动态申请!可以引入 permission_handler: ^8.1.6 插件动态申请 camera 权限

//当前权限
Permission permission = Permission.camera;
//权限的状态
PermissionStatus status = await permission.status;
if (status.isUndetermined) {
  //发起权限申请
  PermissionStatus status = await permission.request();
  if (status.isGranted) {
    return true;
  }
} else {
  return true;
}

release 包需要添加混淆规则

-keeppackagenames com.netease.nis.ocr
keep class com.netease.nis.**{*;}
-dontwarn com.netease.nis.ocr.**

iOS 配置

在 flutter 工程对应的 example/ios/Runner/info.plist 里 ,添加

<key>NSPhotoLibraryUsageDescription</key> 
<string></string> 
<key>NSCameraUsageDescription</key>
<string></string>

调用示例 #

class OcrDetectExample extends StatefulWidget {
  @override
  _OcrDetectExampleState createState() => _OcrDetectExampleState();
}

class _OcrDetectExampleState extends State<OcrDetectExample> {
  final OcrPluginFlutter ocrFlutterPlugin = new OcrPluginFlutter();
  
  Image _imageFront = Image.asset("images/detectBorder.png");

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ocrFlutterPlugin.init("易盾业务id", 120);
      ocrFlutterPlugin.setScanType(1);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('易盾身份证采集'),
        ),
        body: new SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: new Center(
            child: Center(
              child: new Column(
                children: [showFaceImageWidget(),showOcrDetectWidget(), startDetectButton()],
              ),
            ),
          ),
        ),
      ),
    );
  }
  
  // ocr 身份证识别区域
    Widget showOcrDetectWidget() {
        if (defaultTargetPlatform == TargetPlatform.iOS) {
            return Container(
            padding: EdgeInsets.only(top: 100,left: 10,right: 10),
            width: sizeWindow.width,
            height: 400,
            child: _imageFront);
        }
        return Text('$defaultTargetPlatform is not yet supported by this plugin');
  }

  Widget showFaceImageWidget() {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return Container(
        alignment: Alignment.center,
        child: PlatformViewLink(
          viewType: "platform-view-ocr",
          surfaceFactory: (context, controller) {
            return AndroidViewSurface(
              controller: controller as AndroidViewController,
              gestureRecognizers: const <
                  Factory<OneSequenceGestureRecognizer>>{},
              hitTestBehavior: PlatformViewHitTestBehavior.opaque,
            );
          },
          onCreatePlatformView: (params) {
            return PlatformViewsService.initExpensiveAndroidView(
              id: params.id,
              viewType: "platform-view-ocr",
              layoutDirection: TextDirection.ltr,
              creationParams: {},
              creationParamsCodec: const StandardMessageCodec(),
              onFocus: () {
                params.onFocusChanged(true);
              },
            )
              ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
              ..create();
          },
        ),
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      return new Center(
        child: Container(
          child: UiKitView(
            viewType: 'com.flutter.ocr.imageview',
            // 身份证扫描框的坐标
            creationParams: {
              "width": sizeWindow.width,
              "height": 400,
              "x":5,
              "y":50,
              // "radius": "100",
            },
            //参数的编码方式
            creationParamsCodec: const StandardMessageCodec(),
          ),
        ),
      );
    }
    return Text('$defaultTargetPlatform is not yet supported by this plugin');
  }

  Widget startDetectButton() {
    return new Container(
      child: SizedBox(
        child: new TextButton(
          onPressed: () {
            startLive();
          },
          child: Text("开始采集"),
        ),
        width: double.infinity,
        height: 49,
      ),
      margin: EdgeInsets.fromLTRB(40, 5, 40, 5),
    );
  }

  void startLive() {
    ocrFlutterPlugin.startScanner();
  }
}

更多使用场景请参考 demo

SDK 方法说明 #

1 初始化活体检测 #

代码说明:

// 初始化对象
final OcrPluginFlutter ocrFlutterPlugin = new OcrPluginFlutter(); 
ocrFlutterPlugin.init("businessID", “timeout”);

参数说明:

  • options 基础参数:

    参数 类型 是否必填 默认值 描述
    businessID String 易盾分配的业务id
    timeout int 120秒 身份证采集超时时间
    isDebug bool false 是否打开debug开关

2 设置检测类型 #

代码说明:

ocrFlutterPlugin.setScanType(int scanType);

参数说明

  • options 基础参数:

    参数 类型 是否必填 默认值 描述
    scanType int 1 检测类型:1、身份证正面 0、身份证国徽面

3 开始身份证采集 #

代码说明:

ocrFlutterPlugin.startScanner();

4 停止身份证采集 #

代码说明:

ocrFlutterPlugin.stopScanner();

5 检测状态监听 #

代码说明:

var eventChannel = const EventChannel("yd_ocr_flutter_event_channel")

eventChannel.receiveBroadcastStream().listen(_onData, onError: _onError);
   
void _onData(response) {
    if (response is Map) {
      if (mounted) {
        setState(() {
          var type = response["type"];
          if (type == "success") {
            if (kDebugMode) {
              print("检测成功${response["picturePath"]}");
            }
            Navigator.of(context).pop(response["picturePath"]);
          } else if (type == "exception") {
            if (kDebugMode) {
              print("检测异常${response["message"]}");
            }
          } else if (type == "overTime") {
            if (kDebugMode) {
              print("检测超时");
            }
          }
        });
      }
    }
}
  • response 监听回调类型说明(Android)

    类型 描述 配合字段
    success 检测成功 picturePath:图片存储的地址
    exception 发生异常 code:错误码 message:错误信息
    overTime 超时,超过设置的限制时间

6 资源释放 #

Android 特有,建议放在 dispose 生命周期

代码说明:

void dispose() {
    if (defaultTargetPlatform == TargetPlatform.android) {
      //android需要释放资源,否则会引发内存泄露
      ocrFlutterPlugin.destroy();
    }
    super.dispose();
  }
1
likes
125
pub points
53%
popularity

Publisher

unverified uploader

ocr_plugin_flutter project.

Homepage

Documentation

API reference

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on ocr_plugin_flutter