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

Mah*_*ahi 12 dart flutter

我实际上是在尝试将拍摄的图像转换ImagePickerbase64图像.我总是得到错误.

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)
Run Code Online (Sandbox Code Playgroud)

我正在使用的代码是这个.

     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);
Run Code Online (Sandbox Code Playgroud)

拜托,有人可以告诉我,我犯了什么错误.

非常感谢,Mahi

Mah*_*ahi 28

嗨,我刚刚更改了我的代码如下,

List<int> imageBytes = widget.fileData.readAsBytesSync();
print(imageBytes);
String base64Image = base64Encode(imageBytes);
Run Code Online (Sandbox Code Playgroud)

这现在工作正常.

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

 List<int> imageBytes = await widget.fileData.readAsBytes();
Run Code Online (Sandbox Code Playgroud)

  • 嗨@ArnoldParge 它来自```dart: convert``` API 如果你想查看它。 (3认同)
  • 你从哪里得到函数`base64Encode()`? (2认同)

小智 14

您可以简单地将图像更改为字符串:

final bytes = Io.File(imageBytes.path).readAsBytesSync();

String img64 = base64Encode(bytes);
Run Code Online (Sandbox Code Playgroud)


小智 12

就我而言,我首先使用image_picker选择图像,然后使用这些代码行将图像转换为 base64。

 final bytes = File(image!.path).readAsBytesSync();
                          String base64Image =  "data:image/png;base64,"+base64Encode(bytes);

                          print("img_pan : $base64Image");
Run Code Online (Sandbox Code Playgroud)

图像选择器代码:

  final ImagePicker _picker = ImagePicker();
  XFile? image;

                  Container(
                    margin: const EdgeInsets.all(15.0),
                    padding: const EdgeInsets.all(3.0),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.black),
                      borderRadius: BorderRadius.all(Radius.circular(5.h))
                    ),
                    child:InkWell(
                    onTap: () async {
                      image = await _picker.pickImage(
                          source: ImageSource.gallery);
                      setState(() {});
                    },
                    child: image != null
                        ? Image.file(
                            File(image!.path),
                            height: 100.h,
                            width: 100.w,
                          )
                        : Image.asset(
                            'assets/image_icon.png',
                            height: 100.h,
                            width: 100.w,
                      fit: BoxFit.fill,
                          ),
                  ),),
Run Code Online (Sandbox Code Playgroud)