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
相关产品推荐
相关产品推荐

