Dart 如何在Flatter中将图像转换为base64图像?

Dart 如何在Flatter中将图像转换为base64图像?,dart,flutter,Dart,Flutter,实际上,我正在尝试将颤振中的ImagePicker拾取的图像转换为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 _F

实际上,我正在尝试将颤振中的
ImagePicker
拾取的图像转换为
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);
文件文件数据;
/////////////...........
新容器(
孩子:新未来建设者(
未来:图像文件,
生成器:(BuildContext上下文,异步快照){
如果(snapshot.connectionState==connectionState.done&&
snapshot.data!=null){
fileData=snapshot.data;
退回新货柜(
高度:MediaQuery.of(context).size.height/2,
宽度:MediaQuery.of(context).size.width,
边距:所有常数边集(4.0),
装饰:新盒子装饰(
图片:新装饰图片(
映像:新文件映像(snapshot.data,),
适合:BoxFit.cover
),
),
);
}else if(snapshot.error!=null){
返回新列(子项:[
centerWidget(“选择图像、音频或视频”),
_圆变星()
]);
}否则{
返回新列(子项:[
centerWidget(“选择图像、音频或视频”),
_圆变星()
]);
}
},
),
),
/////////////////
File imageFile=新文件(widget.fileData.uri.toString());
List imageBytes=imageFile.readAsBytesSync();
字符串base64Image=base64Encode(imageBytes);
请问,有人能告诉我哪里出了错吗

非常感谢,,
Mahi

嗨,我刚刚更改了代码,如下所示

List<int> imageBytes = widget.fileData.readAsBytesSync();
print(imageBytes);
String base64Image = base64Encode(imageBytes);
List imageBytes=widget.fileData.readAsBytesSync();
打印(图像字节);
字符串base64Image=base64Encode(imageBytes);
现在这一切都很好

最好异步读取,因为映像可能非常大,这可能会导致主线程阻塞

 List<int> imageBytes = await widget.fileData.readAsBytes();
List imageBytes=wait widget.fileData.readAsBytes();

您只需将图像更改为字符串:

final bytes=Io.File(imageBytes.path).readAsBytesSync();
字符串img64=base64Encode(字节);
容器(
儿童:新的手势检测器(
onTap:()异步{
聚焦范围(上下文)
.requestFocus(新的FocusNode());
等待getImage();
},
孩子:新中心(
子项:_image==null
?新堆栈(
儿童:[
新中心(
孩子:新CircleAvatar(
半径:80.0,
背景颜色:
常量颜色(0xFF778899),
),
),
新中心(
子:图标(
Icons.perm_标识,
尺寸:120,
),
),
],
)
:新CircleAvatar(
半径:60,
孩子:斜坡(
子对象:对齐(
高度系数:0.8,
宽度系数:1.0,
子项:新的Image.file(_Image),
),
),
),
),
),
),
Future getImage()异步{
UserService userRestSrv=UserService();
PickedFile image=await ImagePicker().getImage(来源:ImageSource.gallery,imageQuality:50);
如果(图像!=null){
设置状态(){
_image=文件(image.path);
});
final bytes=文件(image.path).readAsBytesSync();
字符串img64=base64Encode(字节);
var responseProfileImage=await userRestSrv.updateImage(userId,img64);
if(responseProfileImage!=null&&responseProfileImage.data['ResponseCode']=“00”)
showMessage('Profile Image not upload',false);
}
}

您尝试读取的文件不存在或应用程序没有读取权限。这个错误似乎与base64Thanks@GünterZöchbauer,但文件存在于指定的路径中,和显示在手机上,但无法将图像转换为base64当错误显示该文件无法读取时,它仍然与base64无关。嗨@zoechi是否有其他解决方案,以便我可以将图像文件转换为base64编码。谢谢@zoechi,你很惊讶路径被修改,我删除了行
fileimagefile=newfile(widget.fileData.uri.toString())
并将我的代码更改为
List imageBytes=widget.fileData.uri.readAsBytesSync()现在正在运行。您从哪里获得函数
base64Encode()
?hi@ArnoldParge它来自
dart:convert
API,如果您想查看它的话。
Container(
                            child: new GestureDetector(
                              onTap: () async {
                                FocusScope.of(context)
                                    .requestFocus(new FocusNode());
                                await getImage();
                              },
                              child: new Center(
                                child: _image == null
                                    ? new Stack(
                                        children: <Widget>[
                                          new Center(
                                            child: new CircleAvatar(
                                              radius: 80.0,
                                              backgroundColor:
                                                  const Color(0xFF778899),
                                            ),
                                          ),
                                          new Center(
                                            child: Icon(
                                              Icons.perm_identity,
                                              size: 120,
                                            ),
                                          ),
                                        ],
                                      )
                                    : new CircleAvatar(
                                        radius: 60,
                                        child: ClipOval(
                                          child: Align(
                                            heightFactor: 0.8,
                                            widthFactor: 1.0,
                                            child: new Image.file(_image),
                                          ),
                                        ),
                                      ),
                              ),
                            ),
                          ),

Future getImage() async {
    UserService userRestSrv = UserService();

    PickedFile image = await ImagePicker().getImage(source: ImageSource.gallery, imageQuality: 50);

    if (image != null) {
      setState(() {
        _image = File(image.path);
      });

      final bytes = File(image.path).readAsBytesSync();

      String img64 = base64Encode(bytes);
      var responseProfileImage = await userRestSrv.updateImage(userId, img64);

      if (responseProfileImage != null && responseProfileImage.data['ResponseCode'] == "00")
        showMessage('Profile Image not uploaded', false);
    }
  }