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

使用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 的指定位置(示例为左上角),再写入本地文件:

  1. 确保 pubspec.yaml 已添加依赖:image、path_provider
  2. 合并并写入代码:
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:39:56