flutter开发实战-人脸识别相机使用
当需要拍摄的时候,需要检测到人脸再进行后续的操作,这里使用的是face_camera
一、引入face_camera
在工程的pubspec.yaml中引入插件
# 检测人脸
face_camera: ^0.0.8
iOS端需要设置相关权限
在info.plist文件中,设置相机等权限
<key>NSCameraUsageDescription</key>
<string>Take a photo for display</string>
<key>NSMicrophoneUsageDescription</key>
<string>Take a video for display</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Read your photos for display</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
二、人脸识别相机使用
第一步是在main.dart中初始化face_camera
void main() async{
WidgetsFlutterBinding.ensureInitialized(); //Add this
await FaceCamera.initialize(); //Add this
runApp(const MyApp());
}
然后在应用程序中渲染组件,设置onCapture回调。
@override
Widget build(BuildContext context) {
return Scaffold(
body: SmartFaceCamera(
autoCapture: true,
defaultCameraLens: CameraLens.front,
message: 'Center your face in the square',
onCapture: (File? image){
},
)
);
}
完整代码如下
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:face_camera/face_camera.dart';
class FaceCameraPage extends StatefulWidget {
const FaceCameraPage({Key? key}) : super(key: key);
@override
State<FaceCameraPage> createState() => _FaceCameraPageState();
}
class _FaceCameraPageState extends State<FaceCameraPage> {
File? _capturedImage;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('FaceCamera example app'),
),
body: Builder(builder: (context) {
if (_capturedImage != null) {
return Center(
child: Stack(
alignment: Alignment.bottomCenter,
children: [
Image.file(
_capturedImage!,
width: double.maxFinite,
fit: BoxFit.fitWidth,
),
ElevatedButton(
onPressed: () => setState(() => _capturedImage = null),
child: const Text(
'Capture Again',
textAlign: TextAlign.center,
style:
TextStyle(fontSize: 14, fontWeight: FontWeight.w700),
))
],
),
);
}
return SmartFaceCamera(
autoCapture: true,
defaultCameraLens: CameraLens.front,
onCapture: (File? image) {
setState(() => _capturedImage = image);
},
onFaceDetected: (Face? face) {
//Do something
},
messageBuilder: (context, face) {
if (face == null) {
return _message('Place your face in the camera');
}
if (!face.wellPositioned) {
return _message('Center your face in the square');
}
return const SizedBox.shrink();
});
}),
);
}
Widget _message(String msg) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 55, vertical: 15),
child: Text(msg,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14, height: 1.5, fontWeight: FontWeight.w400)),
);
}
三、小结
flutter开发实战-人脸识别相机使用
学习记录,每天不停进步。