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

Flutter中takePicture异常:人脸识别图片转InputImage失败

人脸识别应用图片转换与处理问题修复

从日志和代码中能定位到两个核心问题:

  1. 无效路径导致文件创建失败:代码中硬编码了不存在的路径'path/to/image.jpg',系统无法找到对应目录创建文件,抛出PathNotFoundException。
  2. 变量引用错误:processCameraImage方法中调用_faceDetector.processImage时,传入了未定义的_inputImage变量,实际应该使用方法参数inputImage。

修复后的拍照按钮代码

floatingActionButton: FloatingActionButton(
  onPressed: () async {
    final picture = await controller!.takePicture();
    final _capimg = File(picture.path);
    
    // 复制图片到临时目录(若无需复制可直接使用原路径)
    final directory = await getTemporaryDirectory();
    final path = '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
    final file = await _capimg.copy(path);

    print('The captured image path is: ${_capimg.path}');
    print('Copied image path: ${file.path}');

    setState(() {
      _imageFile = _capimg;
      _imagePath = path;
    });

    // 直接用已存在的文件路径创建InputImage
    final inputImage = InputImage.fromFilePath(_imagePath);
    print('The input image is: ${inputImage.metadata?.size}');

    await processCameraImage(inputImage);
  },
  tooltip: 'Capture',
  child: Icon(Icons.camera_alt),
),

修复后的processCameraImage方法

Future<void> processCameraImage(InputImage inputImage) async {
  if (_isCameraReady && !_detectingFaces) {
    try {
      setState(() {
        _detectingFaces = true;
      });
      // 使用方法传入的inputImage参数
      final faces = await _faceDetector.processImage(inputImage);
      if (faces.isNotEmpty) {
        setState(() {
          _faces = faces;
        });
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        _detectingFaces = false;
      });
    }
  }
}

额外优化说明

  • 移除了无效的空文件创建逻辑,InputImage.fromFilePath仅需已存在的文件路径即可
  • 将await与then混合的写法改为顺序await,提升代码可读性
  • 使用copy方法替代手动字节读写,简化文件复制流程

内容的提问来源于stack exchange,提问作者Nanda Y

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:05:04