How do I convert an image to base64 and base64 to image? The way I do it doesn't work
1,822
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();
Author by
R TG
Updated on December 08, 2022Comments
-
R TG over 1 year
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.