flutter 处理前置摄像头拍出来的图片翻转问题,截取正方形图片问题

最近在做flutter项目的时候用到前置摄像头,拍摄的时候拍出来的图片是翻转的,找到很多办法都没有解决方案。找来找去就找到了image_editor插件

现在贴上代码:

Future<String> takePicture() async {
    if (controller == null) return "";
    if (!controller!.value.isInitialized) {
      return "null";
    }

    final Directory extDir = await getApplicationDocumentsDirectory();
    final String dirPath = '${extDir.path}/Pictures/flutter_test';

    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${timestamp()}.jpg';

    if (controller!.value.isTakingPicture) {
      return "";
    }
    try {
      XFile file = await controller!.takePicture();
      String path = file.path;

      Uint8List? bytes = await file.readAsBytes();
      var image = img.decodeImage(bytes);
      // image?.disposeMethod = DistanceMode.further as img.DisposeMode;
      // image
      if (cameras[cameraDirection].lensDirection == CameraLensDirection.front) {
        /// 前置摄像头处理,后置摄像头一般不会出现问题
        // ImageEditorOption option = ImageEditorOption();
        ImageEditorOption option = ImageEditorOption();
        /// 翻转配置
        option.addOption(FlipOption(horizontal: true));
        bytes = await ImageEditor.editImage(
            image: bytes!, imageEditorOption: option);

        await File(path).delete();
        File(path).writeAsBytesSync(bytes!);
      }
      if (image != null) {
        // await clipImage(file.path, image.width, image.height);
      }

      var offset = (image!.height - image.width) / 2;
      ImageProperties properties =
          await FlutterNativeImage.getImageProperties(path);
      properties.orientation = ImageOrientation.flipHorizontal;

      // File(file.path).writeAsBytesSync(bytes);
      /// 截取图片
      File cropedFile = await FlutterNativeImage.cropImage(
          file.path, 0, offset.round(), image.width, image.width);

      // img.bakeOrientation(image);

      return cropedFile.path;
    } on CameraException catch (e) {
      return e.toString();
    }
    return "";
  }

 记录一下解决方案

猜你喜欢

转载自blog.csdn.net/lck8989/article/details/126633024