You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中已完成图片选取后,如何将PNG转换为WebP格式?

实现Flutter图片转WebP格式

要将选中的图片转换为WebP格式,你可以使用flutter_image_compress库完成格式转换,以下是具体修改步骤:

1. 添加依赖

在pubspec.yaml的dependencies节点中添加:

flutter_image_compress: ^2.1.0

执行flutter pub get完成依赖安装。

2. 编写图片转换函数

新增一个将本地图片文件转成WebP格式的工具函数:

Future<File?> convertImageToWebP(File imageFile) async {
  try {
    final result = await FlutterImageCompress.compressAndGetFile(
      imageFile.absolute.path,
      '${imageFile.parent.path}/${DateTime.now().millisecondsSinceEpoch}.webp',
      format: CompressFormat.webp,
      quality: 80, // 可根据需求调整质量,范围0-100,数值越高质量越好体积越大
    );
    return result;
  } catch (e) {
    print('WebP转换失败: ${e.toString()}');
    return null;
  }
}

3. 修改图片选取逻辑

在你的_pickImages方法中加入转换逻辑,替换原有文件处理流程:

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 {
      // 用户取消选择
      return;
    }
  } catch (e) {
    print(e.toString());
    return;
  }

  if (!mounted) return;

  List<String> convertedWebPPaths = [];
  for (var imageFile in resultList) {
    bool isComply = await CommonMethods.isImageHorizontal(imageFile);
    if (isComply) {
      // 转换为WebP格式
      File? webpFile = await convertImageToWebP(imageFile);
      if (webpFile != null) {
        String webpPath = webpFile.path;
        if (!selectedImages.contains(webpPath)) {
          convertedWebPPaths.add(webpPath);
        } else {
          Logger().wtf("文件已存在");
        }
      }
    } else {
      // 处理非横屏图片的错误提示
    }
  }

  setState(() {
    selectedImages.addAll(convertedWebPPaths);
  });
}

额外说明

  • 转换后的WebP文件会保存在原图片的同一目录下,用时间戳命名避免重复。
  • 若不需要保留原图片文件,可在转换成功后调用imageFile.delete()删除原文件。

内容的提问来源于stack exchange,提问作者Shakila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:07:40