Flutter从数据库读取图片报错:无法检测图片文件格式
问题:展示数据库存储的图片时格式检测失败
错误提示:
Failed to detect image file format using the file header.
File header was [0x5b 0x31 0x30 0x30 0x2c 0x20 0x39 0x37 0x2c 0x20].
Image source: encoded image bytes
原获取转换图片的代码:
final String imageString = data['image']['data'].toString(); final List<int> list = imageString.codeUnits; image = Uint8List.fromList(list);
原Widget展示图片的代码:
Image( image: MemoryImage(image), width: 165, height: 165, ),
问题原因:
错误里的文件头字节对应的ASCII是[100, 97, ,说明你把图片字节列表的字符串表示转换成了字节,而非图片的原始字节数据。data['image']['data']本身就是图片的原始整数字节列表,调用.toString()后会变成类似"[100,97,...]"的字符串,再取codeUnits得到的是这个字符串每个字符的编码,自然不符合图片格式要求。
解决方案:
直接使用原始的整数列表转换为Uint8List,不要调用.toString():
final List<int> imageBytes = data['image']['data'] as List<int>; image = Uint8List.fromList(imageBytes);
Widget展示部分的代码无需修改,保持原样即可正常加载图片。
内容的提问来源于stack exchange,提问作者Eder Savillon
相关产品推荐
相关产品推荐

