使用img.decodePng()时_UnmodifiableByteDataView转Uint8List失败求助
解决ByteData转Uint8List错误及图片合并写入方案
错误原因
rootBundle.load() 返回的是 ByteData 类型,直接用 as Uint8List 强制转换会失败——因为实际返回的是 _UnmodifiableByteDataView 实例,并非原生的 Uint8List。
正确读取图片的方式
通过 ByteData 的 buffer.asUint8List() 方法转换为 Uint8List,再传给图片解码方法:
// 读取第一张图片 var byteData1 = await rootBundle.load('packages/gm_firebase/images/cards/card_template.png'); Uint8List imgBytes1 = byteData1.buffer.asUint8List(); final image1 = img.decodePng(imgBytes1); // 读取第二张图片(替换为你的实际路径) var byteData2 = await rootBundle.load('packages/gm_firebase/images/cards/image2.png'); Uint8List imgBytes2 = byteData2.buffer.asUint8List(); final image2 = img.decodePng(imgBytes2);
图片合并与写入文件
假设要把 image2 叠加到 image1 的指定位置(示例为左上角),再写入本地文件:
- 确保
pubspec.yaml已添加依赖:image、path_provider - 合并并写入代码:
import 'dart:io'; import 'package:image/image.dart' as img; import 'package:path_provider/path_provider.dart'; // 合并图片并写入 if (image1 != null && image2 != null) { // 将image2复制到image1的(0,0)位置,可自行调整坐标 img.copyInto(image1, image2, dstX: 0, dstY: 0); // 编码为PNG格式字节 Uint8List mergedBytes = img.encodePng(image1); // 获取应用文档目录作为存储路径 Directory appDir = await getApplicationDocumentsDirectory(); File outputFile = File('${appDir.path}/merged_card.png'); // 写入文件 await outputFile.writeAsBytes(mergedBytes); }
内容的提问来源于stack exchange,提问作者APEGamer
相关产品推荐
相关产品推荐

