我正在尝试在 Flutter 中压缩图像并将其缩放为某种格式(16/9) 对于压缩,我使用 FlutterImageCompress 库。 但是,这给我的返回值为零。 文档说: "有时,压缩会返回null。您应该检查文件是否可以读/写,并且目标文件的父文件夹必须存在。
例如,在Android/iOS上使用path_provider插件访问某些应用程序文件夹,并使用权限插件请求访问SD卡的权限。” https://pub.dev/packages/flutter_image_compress#troubleshooting
所以我尝试在压缩之前创建文件夹。我的代码看起来像这样:
final appDocDir = await getApplicationDocumentsDirectory();
pickedFile = File(filepath); //retrieved with filepicker
Directory tempDir = Directory('${appDocDir.path}/temp/');
if (!tempDir.existsSync()) {
tempDir.createSync(recursive: true);
}
pickedFile = await FlutterImageCompress.compressAndGetFile(
pickedFile.absolute.path,
"${appDocDir.absolute}/temp.jpg",
quality: 5,
);
File file = File("${appDocDir.absolute}/temp.jpg");
print("File Size: ${file.lengthSync()}");
我的目标是File文件末尾包含压缩文件,以便我可以上传它。
我已经尝试创建应手动写入结果的文件夹,但这并没有改变任何东西。我也不关心压缩后图像的最终位置,因为在文件上传后它会再次被删除。
如本解决方案所示,您也可以实现它。 https://stackoverflow.com/a/64690920
您只需将新文件保存在与要压缩的原始文件相同的路径上即可。这样您就可以确保您在此位置具有写入权限。
您的代码的整个过程如下:
final appDocDir = await getApplicationDocumentsDirectory();
pickedFile = File(ref.watch(imageProvider).image!.path!);
final filePath = pickedFile.absolute.path;
final lastIndex = filePath.lastIndexOf(new RegExp(r'.jp'));
final splitted = filePath.substring(0, (lastIndex));
final outPath = "${splitted}_out${filePath.substring(lastIndex)}";
await FlutterImageCompress.compressAndGetFile(
pickedFile.absolute.path,
outPath,
quality: 5,
);
File file = File(outPath);
print("File Size: ${file.lengthSync()}");