如何使用image_picker语言 - Flutter压缩图像



我正在构建一个图像压缩器。为此,我使用了flutter image_picker包,它有一个名为imageQuality的属性,可以减少图像的大小。

我想要实现的是首先通过imagePicker上传图像,然后压缩它。所以我可以得到原始和压缩的大小(之前和之后)。

目前它所做的是在上传/挑选图像时压缩大小。那是我不想要的。我怎么能分成两步(首先上传,然后使用图像质量参数压缩大小)

void selectImage() async {
final imagePicker = await ImagePicker().pickImage(source: ImageSource.gallery, imageQuality: 80); // upload and compress (I want to split this process)
photoSize = await getFileSize(imagePicker!.path, 1);
setState(() {
_file = File(imagePicker.path);
});
}

根据您的问题,为什么不使用Image_compression_flutter来压缩图像后,您选择的图像与imageQuality: 100.

通过使用另一个压缩函数,可以压缩图像并得到压缩后的图像作为输出。

请查看下面的代码

您可以查看此链接获取完整的示例代码。

您可以尝试使用以下函数压缩图像。

请参考下面的插件来压缩图像

flutter_image_compress: ^ 0.7.0

Future<File> compressImage(File file) async {
final filePath = file.absolute.path;
final lastIndex = filePath.lastIndexOf(new RegExp(r'.png|.jp'));
final splitted = filePath.substring(0, (lastIndex));
final outPath = "${splitted}_out${filePath.substring(lastIndex)}";
if (lastIndex == filePath.lastIndexOf(new RegExp(r'.png'))) {
final compressedImage = await FlutterImageCompress.compressAndGetFile(
filePath, outPath,
minWidth: 1000,
minHeight: 1000,
quality: 50,
format: CompressFormat.png);
return compressedImage;
} else {
final compressedImage = await FlutterImageCompress.compressAndGetFile(
filePath,
outPath,
minWidth: 1000,
minHeight: 1000,
quality: 50,
);
return compressedImage;
}
}
File photoCompressedFile =
await compressImage(File(pickedImage.path));
print("Path of Compressed File: ${photoCompressedFile.path}");

最新更新