You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flutter google_mlkit_face_detection裁剪检测到的人脸并保存

裁剪并保存检测到的人脸区域

要实现人脸裁剪并保存,你可以借助image库处理图片裁剪,结合path_provider管理文件存储路径。以下是完整的实现步骤和代码:

1. 添加依赖

在pubspec.yaml中添加所需依赖:

dependencies:
  flutter:
    sdk: flutter
  image: ^4.0.17 # 版本可按需更换为最新版
  path_provider: ^2.1.1
  google_mlkit_face_detection: ^0.10.0 # 确保已添加此依赖

2. 完整代码实现

修改你的_processImage函数,加入裁剪和保存逻辑:

import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';

Future<void> _processImage(InputImage inputImage) async {
  final faces = await _faceDetector.processImage(inputImage);
  if (faces.isNotEmpty) {
    final boundingBox = faces.first.boundingBox;
    int left = boundingBox.left.toInt();
    int top = boundingBox.top.toInt();
    int width = boundingBox.width.toInt();
    int height = boundingBox.height.toInt();

    // 加载原始图片数据
    img.Image? originalImage;
    if (inputImage.file != null) {
      // 处理来自文件的InputImage
      final file = File(inputImage.file!.path);
      final imageBytes = await file.readAsBytes();
      originalImage = img.decodeImage(imageBytes);
    } else if (inputImage.bytes != null) {
      // 处理来自字节流的InputImage(如相机预览)
      originalImage = img.decodeImage(inputImage.bytes!);
    }

    if (originalImage == null) {
      print('无法加载原始图片');
      return;
    }

    // (可选)坐标适配:如果InputImage尺寸与原始图片实际尺寸不一致,需调整裁剪坐标
    // 示例:假设原始图片实际尺寸为imageWidth x imageHeight
    // final inputSize = inputImage.metadata?.size;
    // if (inputSize != null) {
    //   final scaleX = originalImage.width / inputSize.width;
    //   final scaleY = originalImage.height / inputSize.height;
    //   left = (left * scaleX).toInt();
    //   top = (top * scaleY).toInt();
    //   width = (width * scaleX).toInt();
    //   height = (height * scaleY).toInt();
    // }

    // 裁剪人脸区域
    final croppedImage = img.copyCrop(
      originalImage,
      x: left,
      y: top,
      width: width,
      height: height,
    );

    // 保存裁剪后的图片到本地
    final directory = await getApplicationDocumentsDirectory();
    final savePath = '${directory.path}/cropped_face_${DateTime.now().millisecondsSinceEpoch}.png';
    final croppedFile = File(savePath);
    await croppedFile.writeAsBytes(img.encodePng(croppedImage));

    print('人脸已成功裁剪并保存至:$savePath');
  }
}

3. 注意事项

  • 坐标适配:如果InputImage的尺寸(如相机预览尺寸)与原始图片实际尺寸不一致,必须通过比例转换调整裁剪坐标,否则会出现裁剪区域偏移的问题。
  • 权限配置:
    • Android:若需保存到外部公共存储,需在AndroidManifest.xml中添加<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>(Android 13+可使用READ_MEDIA_IMAGES替代)。
    • iOS:在Info.plist中添加NSPhotoLibraryAddUsageDescription权限描述,允许将图片保存到相册。
  • 图片格式:示例中使用PNG格式保存,你也可以通过img.encodeJpg(croppedImage, quality: 90)改为JPG格式,并调整压缩质量。

内容的提问来源于stack exchange,提问作者Md Zihad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:12:51