首页 > 解决方案 > 如何将图像转换为 base64 和 base64 为图像?我这样做的方式行不通

问题描述

这是一个示例代码。

var image = await ImagePicker.pickImage(source: ImageSource.camera);
var stringBytes = base64.encode(image.readAsBytesSync());
var bytes = base64.decode(stringBytes);
var newImage = new File.fromRawPath(bytes);
I/flutter (14608): The following FileSystemException was thrown resolving an image codec:
I/flutter (14608): Cannot open file, path = '����*�Exif
I/flutter (14608): 
I/flutter (14608): 
I/flutter (14608): Business
I/flutter (14608): 11:42:34
I/flutter (14608): �
I/flutter (14608):  
I/flutter (14608): ��
I/flutter (14608): ��
I/flutter (14608): %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
I/flutter (14608): ��
I/flutter (14608): $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������
I/flutter (14608): ��ت���U-%�����^
I/flutter (14608): }�m���
I/flutter (14608): u���V�N6R���
I/flutter (14608): j_8}W,1�ڹ�?ܻw^��� ��6��ꗚm���E[ϓ�������>���X�W��y������=�[!��2!ډ�'8�Mk^ܾ��eS�

并且未知字符的列表还在继续。

我究竟做错了什么?

我想将它转换为 base64,因为我要将它添加到数据库中。

标签: dartflutterdecodeencode

解决方案


不,您正在传递图像的内容以创建一个内容为原始路径的新文件,这是行不通的。

new File.fromRawPath确实,根据文档

从原始路径(即操作系统表示的字节序列)创建 File 对象。

您要做的是创建一个文件并将内容存储到该文件中,这可以这样完成(Source):

var imageFile = File('myimage.jpg');
var sink = imageFile.openWrite();
sink.write(bytes);
await sink.flush();
await sink.close();

推荐阅读