简体   繁体   English

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

[英]how to convert an image to base64 image in flutter?

I am actually trying to convert an image picked by ImagePicker in flutter to base64 image.我实际上正在尝试将ImagePicker在 flutter 中选择的图像转换为base64图像。 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)

the code i am using is this one.我正在使用的代码是这个。

     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.拜托,有人能告诉我我在哪里犯了错误吗?

Many thanks, Mahi非常感谢, Mahi

I just changed my code as follows,我只是改变了我的代码如下,

import 'dart:convert';

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

and this is working fine now.这现在工作正常。

It is better to read it asynchronously as the image can be very large which may cause blocking of the main thread最好异步读取,因为图像可能非常大,可能会导致主线程阻塞

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

you can simply change the image to string :您可以简单地将图像更改为字符串:

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

String img64 = base64Encode(bytes);

In my case, i first selected the image using image_picker then use these line of code to convert the image to base64.就我而言,我首先使用image_picker选择图像,然后使用这些代码行将图像转换为 base64。

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

                          print("img_pan : $base64Image");

image_picker code: 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,
                          ),
                  ),),
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);
    }
  }

In case you are trying to manage image/file uploads using Flutter Web, https://pub.dev/packages/file_picker is a better package to go with.如果您尝试使用 Flutter Web 管理图像/文件上传, https ://pub.dev/packages/file_picker 是一个更好的软件包。

As we know, dart:io is not supported on Flutter Web and throws Unsupported operation: _Namespace error.众所周知,Flutter Web 不支持dart:io并抛出Unsupported operation: _Namespace错误。 Hence, using File and reading file's bytes was not an option.因此,使用File和读取文件的字节不是一种选择。 Luckily, the package provides API to convert the uploaded image to Uint8List .幸运的是,该包提供了 API 来将上传的图像转换为Uint8List Here is my implementation:这是我的实现:

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

In case you need to display the local image right away, use Image.memory .如果您需要立即显示本地图像,请使用Image.memory

Image.memory(logoBase64!);
//this is dart code
final bytes = File(image!.path).readAsBytesSync();  
String base64Image = base64Encode(bytes);
print("imgbytes : $base64Image");

//this is flutter code for image picker
Future uploadAll() async {
var bytes = File(image!.path).readAsBytesSync();
String base64Image = base64Encode(bytes);
print('upload proccess started');

var apipostdata = {
  "title": contentController.text.toString().toUpperCase(),
  "book_image": base64Image,
  "book_type": _genderRadioBtnVal,
};
await http
    .post(Uri.parse('http://192.168.29.111:8000/api/book/add_book'),
        body: apipostdata)
    .then((response) {
  var returndata = jsonEncode(response.body);
  if (response.statusCode == 200) {
    print(returndata);
  } else {
    print('failed');
  }
}).catchError((err) {
  setState(() {
    err;
  });
});  }

I see that more than one has already answered the question.我看到不止一个人已经回答了这个问题。 But I allow myself to put my solution and it works for me.但我允许自己提出我的解决方案,它对我有用。 I use file_picker: ^5.0.1我使用file_picker: ^5.0.1

void openFileImageExplorer() async {
    //try {
      final pickedFile = await FilePicker.platform.pickFiles(
          allowedExtensions: ['jpg', 'jpeg', 'png', 'bmp', 'gif']
      );
      if (pickedFile == null) {
        return;
      }

    final file = pickedFile.files.first;

    final bytes = File(file.path!).readAsBytesSync();
    String img64 = base64Encode(bytes);
    setState(() {
      imageBase64 = img64;
    });

    logCat(img64);
    //} catch(ex, trace ){
    //  logError(ex, trace: trace);
    //}
}

And to display the image并显示图像

Image.memory( base64Decode(imageBase64), fit: BoxFit.cover )

and I hope it will help...我希望它会有所帮助......

Here a simple function:这是一个简单的 function:

String convertIntoBase64(File file) {
List<int> imageBytes = file.readAsBytesSync();
String base64File = base64Encode(imageBytes);
return base64File;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM