Flutter中将BASE64字符串转换为图像

4

我已经尝试将BASE64字符串解码为Uint8List

Uint8List _bytes =
    base64.decode('data:image/jpeg;base64,/9j/4AAQ .........');
Image.memory(_bytes);

但是遇到了错误,错误信息为(Error on character :)

无效字符(位于第5个字符处) data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSEhMVFRUV...

我该如何解决这个问题?


1
你需要仅对数据进行 base64.decode,起始于 /9j/4AAQ .........' - pskink
2个回答

20

您正在使用包含逗号后的数据的URI,该URI由RFC-2397定义。 Dart的Uri类基于RFC-3986,因此您不能使用它。请通过逗号拆分字符串并获取其最后部分:

String uri = 'data:image/gif;base64,...';
Uint8List _bytes = base64.decode(uri.split(',').last);

示例代码对初学者非常有用☺️

GestureDetector(
onTap:(){
showDialog(context: context, builder: (context){
var img64 = snapshot.getStudentDetailModel?.courseDetails?.pscPaymetSlip;
final decodestring = base64Decode('$img64'.split(',').last);
Uint8List encodeedimg = decodestring;
  return AlertDialog(
         contentPadding: EdgeInsets.zero,
         content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                  Container(
                   height:300,
                   decoration: BoxDecoration(
                   image: DecorationImage(
                   fit: BoxFit.cover,
                   image: MemoryImage(encodeedimg))),),],),);
                                      });
                                      },
                   child:Text('View',                                                 textAlign:TextAlign.end),),

0

你可以试着这样做

final UriData data = Uri.parse(plFile.path!).data!;
print(data.isBase64);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接