如何将映像转换为base64并将base64转换为image?我的方法行不通

问题描述:

这是示例代码。

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�

和lis未知字符的数量还在继续。

and the list of unknown characters continues.

我在做什么错了?

我想在base64中进行转换,因为我将其添加到数据库中。

I want to convert it in base64 because I am going to add it in a database.

不,不,您正在传递图像的内容以创建一个新的图像。

Nah, you're passing the content of the image to create a new file with the content as raw path, this cannot work.

new File.fromRawPath 可以做到,根据文档:


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

Creates a File object from a raw path, that is, a sequence of bytes as represented by the OS.

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

What you want to do is to create a file and store the content to that file, this can be done like that (Source):

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