本文介绍了如何将图像转换为flutter中的base64图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是在尝试将 ImagePicker 在抖动中拾取的图像转换为 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 .

非常感谢,
Mahi

Many thanks,Mahi

推荐答案

我只是将代码更改为

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 main thread

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

这篇关于如何将图像转换为flutter中的base64图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:58