如何在颤振中将图像转换为 base64 图像? [英] how to convert an image to base64 image in flutter?
本文介绍了如何在颤振中将图像转换为 base64 图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实际上是在尝试将 ImagePicker
在 flutter 中选取的图像转换为 base64
图像.我总是收到错误.
I am actually trying to convert an image picked by ImagePicker
in flutter to base64
image. I am always getting the error.
FileSystemException: Cannot open file, path =
'file:///storage/emulated/0/Download/Abid_Wipro_neemuchwala1-
770x433.jpg' (OS Error: No such file or directory, errno = 2)
E/flutter ( 5042): #0 _File.throwIfError
(dart:io/file_impl.dart:628)
E/flutter ( 5042): #1 _File.openSync
(dart:io/file_impl.dart:472)
E/flutter ( 5042): #2 _File.readAsBytesSync
(dart:io/file_impl.dart:532)
我使用的代码是这个.
File fileData;
/////////////...........
new Container(
child: new FutureBuilder<File>(
future: imageFile,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.data != null) {
fileData = snapshot.data;
return new Container(
height: MediaQuery.of(context).size.height / 2,
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.all(4.0),
decoration: new BoxDecoration(
image: new DecorationImage(
image: new FileImage(snapshot.data,),
fit: BoxFit.cover
),
),
);
} else if (snapshot.error != null) {
return new Column(children: <Widget>[
centerWidget('Choose Image or Audio or Video'),
_circleAvatar()
]);
} else {
return new Column(children: <Widget>[
centerWidget('Choose Image or Audio or Video'),
_circleAvatar()
]);
}
},
),
),
/////////////////
File imageFile = new File(widget.fileData.uri.toString());
List<int> imageBytes = imageFile.readAsBytesSync();
String base64Image = base64Encode(imageBytes);
请谁能告诉我我哪里出错了.
Please, can someone tell me where is it that i am making a mistake .
非常感谢,玛希
推荐答案
我只是把代码改成如下,
I just changed my code as follows,
import 'dart:convert';
List<int> imageBytes = widget.fileData.readAsBytesSync();
print(imageBytes);
String base64Image = base64Encode(imageBytes);
现在一切正常.
最好异步读取,因为图像可能非常大,可能会导致主线程阻塞
It is better to read it asynchronously as the image can be very large which may cause blocking of the main thread
List<int> imageBytes = await widget.fileData.readAsBytes();
这篇关于如何在颤振中将图像转换为 base64 图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文