How do I convert an image to base64 and base64 to image? The way I do it doesn't work

﹥>﹥吖頭↗ 提交于 2019-12-02 05:09:38

问题


This is an example code.

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�

and the list of unknown characters continues.

What am I doing wrong?

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


回答1:


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 does, according to the docs:

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();


来源:https://stackoverflow.com/questions/54233038/how-do-i-convert-an-image-to-base64-and-base64-to-image-the-way-i-do-it-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!