我需要得到的图像使用图像拾取器插件,我需要转换这些图像为WebP使用Flutter 翼,图像拾取器已完成,现在我需要转换图像为WebP,以减少图像大小

this is my code to get the image ,also i added allowCompression: true to reduce the size but ,it doesnt convert the image to webp


Future<void> _pickImages() async {
      List<File> resultList = [];
      try {
        FilePickerResult? result = await FilePicker.platform.pickFiles(
          allowCompression: true,
          type: FileType.custom,
          allowMultiple: true,
          allowedExtensions: ['jpg', 'png', 'jpeg'],
        );

        if (result != null) {
          resultList = result.paths.map((path) => File(path!)).toList();
        } else {
          // User canceled the picker
          return;
        }
      } catch (e) {
        print(e.toString());
        return;
      }

      if (!mounted) return;

      // setState(() {
      for (var i = 0; i < resultList.length; i++) {
        bool isComply = await CommonMethods.isImageHorizontal(resultList[i]);
        // Check if the image is horizontal
        if (isComply) {
          if (!selectedImages.contains(resultList[i].path)) {
            selectedImages.add(resultList[i].path);
          } else {
            Logger().wtf("File Already Exist");
          }
        } else {
          // Show an error for non-horizontal images
        }
      }
      // });
      setState(() {});
    }

推荐答案

要将图像转换为WebP格式,可以使用Ffltter_IMAGE_COMPRESS程序包.下面是一个如何做到这一点的例子:

import 'package:flutter_image_compress/flutter_image_compress.dart';

Future<Uint8List> _compressImage(File imageFile) async {
  final result = await FlutterImageCompress.compressWithList(
    imageFile.readAsBytesSync(),
    minHeight: 1080,
    minWidth: 1080,
    quality: 96,
    rotate: 270,
    format: CompressFormat.webp,
  );
  return result;
}

无需打包即可将图像转换为WebP格式,您可以使用以下命令:

Future<void> _saveWebPImage(Uint8List webPImage, String fileName) async {
  final directory = await getApplicationDocumentsDirectory();
  final filePath = '${directory.path}/$fileName.webp';
  final file = File(filePath);
  await file.writeAsBytes(webPImage);
}

Flutter相关问答推荐

如何更改默认应用程序启动器/启动屏幕

手势捕获的异常:类型';Double';不是类型转换中类型';Double';的子类型

想更新ListView上的索引点击块Flutter

如何在2024年使用Ffltter将用户数据保存在云FireStore中?

为什么Build_Runner的输出为0?

BlocBuilder仅生成一次,并在后续发出时停止重建

Android工作室Flutter 热重新加载更新后不工作

将自定义容器附加到屏幕底部

自定义类提供程序 Riverpod Flutter 中的可变变量

如何使用Riverpod提供程序正确构建搜索栏?

Flutter ListView 在 Column 中工作但在 Row 中不工作

graphql_flutter 错误:非抽象类GraphQLWebSocketChannel缺少实现

如何在两个不同的路由(屏幕)之间正确设置 BlocProvider?

如何验证非表单字段?

如何获取 android 和 Ios (flutter) 的 CircularProgress 指示器?

Flutter如何从左到右连续 Select 多个列表项而不跳过任何

Flutter 用户过滤器

http响应在Flutter 中返回307

Flutter - 检测手指何时进入容器

如何将所有行项目平等地放在一行中?Flutter