Flutter活体检测插件blusalt_liveness_native的使用

Flutter活体检测插件blusalt_liveness_native的使用

blusalt_liveness_native

面部比较和面部检测SDK用于Android和iOS平台。

获取您的活体检测凭证,请访问Blusalt

特性

面部比较(LivenessFacialComparisonType)

  1. 动态活体检测(Motional)

    • 通过要求用户执行特定动作(如张嘴或摇头)来验证活体。
    • 这种方法较为严格,如果尝试通过静止图像绕过动作,可能会被检测到并终止过程。
  2. 静态活体检测(Still)

    • 要求用户将脸部置于摄像头范围内,并基于面部数据点进行活体验证。
    • 相对较不严格。如果用户难以找到正确的摄像头位置,该过程可能不会自动终止,允许用户调整。

面部检测(LivenessDetectionOnlyType)

  1. 动态活体检测(Motional)

  2. 静态活体检测(Still)

  3. 闪光活体检测(Flash)

    • 仅适用于面部检测,不适用于面部比较。
    • 工作方式类似于静态方法,但会增加设备屏幕亮度以增强面部数据点的检测。

使用

pubspec.yaml文件中添加依赖:

dependencies:
  blusalt_liveness_native: ^lastVersion

示例

以下是一个完整的示例,展示了如何使用blusalt_liveness_native插件进行面部比较和面部检测。

import 'dart:convert';

import 'package:blusalt_liveness_native/enums.dart';
import 'package:blusalt_liveness_native/liveness.dart';
import 'package:blusalt_liveness_native/model.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';

import 'base64image.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _livenessPlugin = BlusaltLivenessNative();

  final String clientId = "errereere";
  final String appName = "errerere";
  final String apiKey = "errerererere";
  final bool isDev = false;

  // 如果您希望在到达SDK主页时自动启动SDK而不是让用户点击继续按钮
  final bool startProcessOnGettingToFirstScreen = false;

  @override
  void initState() {
    super.initState();
  }

  Future<BlusaltLivenessResultResponse?> faceComparison() async {
    final Uint8List decodedBytes = base64Decode(base64String);
    BlusaltLivenessResultResponse? response =
        await _livenessPlugin.startFacialComparisonSDK(
            apiKey: apiKey,
            appName: appName,
            clientId: clientId,
            isDev: isDev,
            imageData: decodedBytes,
            startProcessOnGettingToFirstScreen:
                startProcessOnGettingToFirstScreen);
    if (response?.livenessResultType == BlusaltLivenessResultType.success) {
      // 面部比较成功
      String? originalImagePassedToSDKInBase64 =
          response?.comparisonData?.originalImage;
      bool isFaceComparisonPassed =
          response?.comparisonData?.isPassFaceComparison ?? false;

      String? livnessImageInBase64 = response?.faceDetectionData?.imageByte;
      bool isLivnessPassed =
          response?.faceDetectionData?.isPassFaceGenuiness ?? false;
    } else {
      // 面部比较失败
      debugPrint(response?.code ?? '');
      debugPrint(response?.message ?? '');
    }
    return response;
  }

  Future<BlusaltLivenessResultResponse?> livenessDetection() async {
    BlusaltLivenessResultResponse? response =
        await _livenessPlugin.startLivenessDetectionOnlySDK(
            apiKey: apiKey,
            appName: appName,
            clientId: clientId,
            isDev: isDev,
            startProcessOnGettingToFirstScreen:
                startProcessOnGettingToFirstScreen);

    if (response?.livenessResultType == BlusaltLivenessResultType.success) {
      // 活体检测成功
      String? livnessImageInBase64 = response?.faceDetectionData?.imageByte;
      bool isLivnessPassed =
          response?.faceDetectionData?.isPassFaceGenuiness ?? false;
    } else {
      // 活体检测失败
      debugPrint(response?.code ?? '');
      debugPrint(response?.message ?? '');
    }
    return response;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('点击按钮开始活体检测'),
            TextButton(
                onPressed: () {
                  faceComparison();
                },
                child: Text('开始面部比较')),
            SizedBox(
              height: 24,
            ),
            TextButton(
                onPressed: () {
                  livenessDetection();
                },
                child: Text('仅开始面部检测'))
          ],
        ),
      ),
    );
  }
}

安装

Android

步骤1

在Android项目的根目录下创建一个名为github.properties的文件,并填入以下内容。替换其中的值为您的GitHub凭据,并确保授予必要的权限,特别是对于GitHub包。

USERNAME_GITHUB=SampleUsername
TOKEN_GITHUB=SampleClassicToken

步骤2

在项目级别的gradle文件(/android/build.gradle)中添加以下内容:

buildscript {
    ext.kotlin_version = '1.9.+'
    ...

    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.+'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    def githubPropertiesFile = rootProject.file("github.properties")
    def githubProperties = new Properties()
    githubProperties.load(new FileInputStream(githubPropertiesFile))

    repositories {
        maven {
            name "GitHubPackages"
            url 'https://maven.pkg.github.com/Blusalt-FS/Liveness-Only-Android-Package'

            credentials {
                username githubProperties['USERNAME_GITHUB']
                password githubProperties['TOKEN_GITHUB']
            }
        }
    }
}

步骤3

/android/app/build.gradle文件中将最小Android SDK版本改为24(或更高)。

android {
    ...
    defaultConfig {
      ...
      minSdkVersion 24
    }
    ...
}

步骤4

如果您遇到崩溃或超时问题,请在使用ProGuard或启用混淆的情况下,向/android/app/proguard-rules.pro文件中添加以下内容:

-keep public class com.megvii.**{*;}
-keep class net.blusalt.liveness_native.** { *; }

/android/app/build.gradle文件中启用ProGuard:

android {
    
    ...
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    ...
}

注意事项(Android)

如果您在Android上遇到错误,提示“未授权”,当Gradle下载或构建时,请生成一个新的GitHub令牌,该令牌具有克隆、读取和写入仓库的权限,以及访问GitHub包的权限。如果您不确定要勾选哪些选项,请全部勾选。祝您好运!

iOS

最低iOS部署版本

Minimum iOS Deployment = 14

ios/Runner/Info.plist文件中添加以下内容:

<key>NSCameraUsageDescription</key>
<string>您的使用描述</string>

更多关于Flutter活体检测插件blusalt_liveness_native的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter活体检测插件blusalt_liveness_native的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用blusalt_liveness_native插件进行活体检测的示例代码。请注意,此示例假设您已经具备Flutter开发环境,并且已经在pubspec.yaml文件中添加了blusalt_liveness_native依赖项。

1. 添加依赖项

首先,确保在pubspec.yaml文件中添加blusalt_liveness_native依赖项:

dependencies:
  flutter:
    sdk: flutter
  blusalt_liveness_native: ^最新版本号 # 请替换为实际版本号

然后运行flutter pub get来安装依赖项。

2. 导入插件

在您需要使用活体检测的Dart文件中导入插件:

import 'package:blusalt_liveness_native/blusalt_liveness_native.dart';

3. 请求权限(如果需要)

根据您的应用需求,您可能需要在Android和iOS上请求相机权限。这里是一个简单的权限请求示例(使用permission_handler插件):

import 'package:permission_handler/permission_handler.dart';

Future<void> requestCameraPermission() async {
  var status = await Permission.camera.status;
  if (!status.isGranted) {
    var result = await Permission.camera.request();
    if (!result.isGranted) {
      // 处理权限被拒绝的情况
      throw Exception('相机权限被拒绝');
    }
  }
}

别忘了在pubspec.yaml中添加permission_handler依赖项:

dependencies:
  permission_handler: ^最新版本号 # 请替换为实际版本号

4. 使用活体检测插件

以下是一个使用blusalt_liveness_native插件进行活体检测的示例:

import 'package:flutter/material.dart';
import 'package:blusalt_liveness_native/blusalt_liveness_native.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('活体检测示例'),
        ),
        body: Center(
          child: LivenessDetectionButton(),
        ),
      ),
    );
  }
}

class LivenessDetectionButton extends StatefulWidget {
  @override
  _LivenessDetectionButtonState createState() => _LivenessDetectionButtonState();
}

class _LivenessDetectionButtonState extends State<LivenessDetectionButton> {
  Future<void> _startLivenessDetection() async {
    try {
      await requestCameraPermission();

      // 初始化活体检测
      BlusaltLivenessNative.init();

      // 开始活体检测
      var result = await BlusaltLivenessNative.startLivenessDetection(
        onResult: (data) {
          // 处理活体检测结果
          print('活体检测结果: $data');
          if (data['isSuccess']) {
            // 活体检测成功
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('活体检测成功'),
                  content: Text('用户已通过活体检测'),
                  actions: <Widget>[
                    TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text('确定'),
                    ),
                  ],
                );
              },
            );
          } else {
            // 活体检测失败
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text('活体检测失败'),
                  content: Text('用户未通过活体检测'),
                  actions: <Widget>[
                    TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text('确定'),
                    ),
                  ],
                );
              },
            );
          }
        },
      );

      // 打印检测启动结果
      print('启动活体检测结果: $result');
    } catch (e) {
      print('活体检测异常: $e');
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('错误'),
            content: Text('活体检测过程中发生错误: $e'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('确定'),
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _startLivenessDetection,
      child: Text('开始活体检测'),
    );
  }
}

注意事项

  1. 权限处理:确保您的应用已经获得了必要的权限(如相机权限)。
  2. 错误处理:在实际应用中,您可能需要更复杂的错误处理逻辑。
  3. 插件版本:请确保您使用的是blusalt_liveness_native插件的最新稳定版本。
  4. UI优化:根据您的应用需求,您可能需要优化UI设计,以提高用户体验。

希望这个示例能帮助您在Flutter项目中集成和使用blusalt_liveness_native插件进行活体检测。

回到顶部