dart - 如何在 flutter 中将图像转换为base64图像?

我实际上是在尝试将 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);

拜托,谁能告诉我我在哪里犯了错误。

非常感谢, 鲯鳅

最佳答案

我只是将代码更改如下,

import 'dart:convert';

List<int> imageBytes = widget.fileData.readAsBytesSync();
print(imageBytes);
String base64Image = base64Encode(imageBytes);

现在一切正常。

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

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

https://stackoverflow.com/questions/50036393/

相关文章:

http - 在flutter http请求中为所有请求设置默认 header 的最佳方法

android - 如何在 Flutter 中创建可扩展的 ListView

dart - 输入文本时自动扩展的 Flutter 文本字段,然后在达到特定高度时开始滚动文本

api - 为 HTTPClient get() 请求设置超时

Flutter - 容器上的叠加卡片小部件

android - 使用 google dart 语言的原生移动应用程序

dart - Flutter 测试 MissingPluginException

dart - Flutter - 无法构建,因为框架已经在构建

flutter - 如何在不改变 AppBar 的情况下更改 TabBar 的背景颜色?

flutter - 找不到路线生成器