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

Flutter将ui.Image转为文件时出现Invalid image data错误如何解决?

问题排查与修复方案

错误原因

  • 核心错误为字节类型转换不符合PNG文件的格式要求:你调用asUint64List()会将图像缓冲区数据按64位(8字节)为单位的无符号整数输出,而PNG是基于8位单字节的二进制格式,转换后的字节序列完全不符合PNG规范,导致生成的文件非法,加载时抛出无效图像数据异常。
  • 额外风险:toByteData方法存在返回null的可能,未做空判断会增加空异常风险。

修复代码

final tempDir = await getApplicationDocumentsDirectory();
File file = File("${tempDir.path}/image.png");

ui.Image croppedImage = await cropController.croppedBitmap();

final data = await croppedImage.toByteData(
  format: ui.ImageByteFormat.png,
);

// 修正:转为8位字节序列,同时增加非空判断
if (data != null) {
  final bytes = data.buffer.asUint8List();
  file = await file.writeAsBytes(bytes, flush: true);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:04