Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...