我实际上是试图将一个由ImagePicker
在flutter中拾取的图像转换为base64
图像。我总是得到错误。
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);
拜托,谁能告诉我我在哪里犯了错误。
谢谢你,Mahi
9条答案
按热度按时间izkcnapc1#
我只是将代码更改为如下所示,
现在一切正常。
最好异步读取,因为图像可能非常大,这可能会导致主线程阻塞
ckocjqey2#
你可以简单地将图像改为字符串:
rhfm7lfc3#
在我的例子中,我首先使用image_picker选择图像,然后使用这行代码将图像转换为base64。
图像选择器代码(_P):
wz8daaqr4#
如果您尝试使用Flutter Web管理图像/文件上传,https://pub.dev/packages/file_picker是一个更好的包。
正如我们所知,
dart:io
在Flutter Web上不受支持,并抛出Unsupported operation: _Namespace
错误。因此,使用File
和阅读文件的字节不是一个选项。幸运的是,该包提供了API来将上传的图像转换为Uint8List
。以下是我的实现:如果需要立即显示本Map像,请使用
Image.memory
。fruv7luv5#
fzwojiic6#
我看到不止一个人已经回答了这个问题,但是我允许自己提出我的解决方案,它对我很有效。
并显示图像
希望能有所帮助。
flvtvl507#
下面是一个简单的函数:
8ulbf1ek8#
kqqjbcuj9#
尝试使用
Content-Type:charset=utf-8
在我例子中,我在API的头中使用
"Content-Type":"application/json; charset=utf-8"
而
var baseEncode= base64Encode(await file.readAsBytes());
用于编码这对我很有效