如何正确地减小从Flutter相机插件捕获的图像大小

5
我正在使用来自Flutter相机插件的示例代码。我想在捕获图像并将其存储在imageFile变量中后减小图像大小。
我不确定是否有内置功能可用。在他们的文档中没有找到任何信息。
我尝试像下面这样使用Image插件来实现它,但是它无效。当您使用它时,整个应用程序停止运行。
 void onTakePictureButtonPressed() {
    takePicture().then((XFile? file) {
      if (mounted) {
        setState(() {
          resizeImage(file)  // this is what I tried to add to achieve it...
          imageFile = file;
          videoController?.dispose();
          videoController = null;
        });
        if (file != null) showInSnackBar('Picture saved to ${file.path}');
      }
    });
  }



XFile resizeImage(img) {
    var image = imageP.decodeJpg(File(img.path).readAsBytesSync());
    var thumbnail = imageP.copyResize(image, width: 400);
    File(img.path).writeAsBytesSync(imageP.encodeJpg(thumbnail));
    return XFile(img.path);
  }

我还有一个关于叫做 image_crop 的包的成功案例。它不是用来缩小尺寸的,而是用来裁剪的。如果你需要添加裁剪屏幕,你可以使用它。主要函数 cropImage 有 maxHeight 和 maxWidth,这就是你所需要的。https://pub.dev/packages/image_cropper - Mol0ko
1个回答

2

图像包中存在一个错误...我使用了flutter_native_image包,它可以正常工作...

  void onTakePictureButtonPressed() {
        takePicture().then((XFile? file) {
          if (mounted) {
            setState(() {
              resizeImage(file)  // this is what I tried to add to achieve it...
              imageFile = file;
              videoController?.dispose();
              videoController = null;
            });
            if (file != null) showInSnackBar('Picture saved to ${file.path}');
          }
        });
      }

以下是图像压缩函数代码。

Future<XFile> resizeImage(img) async {
    ImageProperties properties =
        await FlutterNativeImage.getImageProperties(img.path);

    File compressedFile = await FlutterNativeImage.compressImage(img.path,
        quality: 90,
        targetWidth: 500,
        targetHeight: (properties.height! * 500 / properties.width!).round());
    
        // delete original file
        try {
          if (await img.exists()) {
            await img.delete();
          }
        } catch (e) {
          // Error in getting access to the file.
        }

    return XFile(compressedFile.path);
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接