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

时间:2018-04-26 06:41:29

标签: 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      _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);

请有人告诉我,我犯了什么错误。

非常感谢, 鳅

5 个答案:

答案 0 :(得分:14)

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

from tkinter import *

root=Tk()

def main_window(win1):
    win1.destroy()
    win2=Frame(root)
    win2.pack()
    label=Label(win2,text="helow").pack()
    Button(win2,text="logout",command=lambda:login_window(win2)).pack()

def login_window(win2):
    win2.destroy()
    win1=Frame(root)
    win1.pack()
    Label(win1,text="Password").pack()
    button1=Button(win1,text="click",command=lambda:main_window(win1)).pack()
    Entry(win1).pack()

def login_window1():
    win1=Frame(root)
    win1.pack()
    Label(win1,text="Password").pack()
    button1=Button(win1,text="click",command=lambda:main_window(win1)).pack()
    Entry(win1).pack()

login_window1()

root.mainloop()

现在工作正常。

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

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

答案 1 :(得分:4)

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

basile.starynkevitch@cea.fr

答案 2 :(得分:1)

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);
    }
  }

答案 3 :(得分:1)

如果您尝试使用 Flutter Web 管理图像/文件上传,https://pub.dev/packages/file_picker 是一个更好的软件包。

我们知道,Flutter Web 不支持 dart:io 并抛出 Unsupported operation: _Namespace 错误。因此,使用 File 和读取文件的字节不是一种选择。幸运的是,该软件包提供了 API 来将上传的图像转换为 Uint8List。这是我的实现:

import 'package:file_picker/file_picker.dart';

...

FilePickerResult? pickedFile;

...

void chooseImage() async {
    pickedFile = await FilePicker.platform.pickFiles();
    if (pickedFile != null) {
      try {
        setState(() {
          logoBase64 = pickedFile!.files.first.bytes;
        });
      } catch (err) {
        print(err);
      }
    } else {
      print('No Image Selected');
    }
}

如果您需要立即显示本地图像,请使用 Image.memory

Image.memory(logoBase64!);

答案 4 :(得分:1)

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

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

                          print("img_pan : $base64Image");

image_picker 代码:

  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,
                          ),
                  ),),
相关问题