首页 > 解决方案 > Flutter:图像 base64 编码 | 颤振中base64编码的字节不准确

问题描述

通过使用 Image Cropper 和 Picker Libraries 的方式,我正在尝试将图像上传到服务器。它工作正常,但在 API 调用期间我需要编码为 base64,与在线图像到 base64 编码工具相比,这里编码的字符串是错误的。所以服务器无法保存数据,即使它保存了它似乎是无效的图像。请帮我解决这个问题。

我已经使用 Postman(在线 base64 图像工具)检查了 API,它工作正常。

代码 :

Future<void> uploadProfileImage() async {
    if (imageFile == null) return;
    String imageFileName = imageFile.path.split("/").last;
    // String base64ProfileImage = base64.encode(imageFile.readAsBytesSync()); // this gives problem
    

    List<int> imageBytes = imageFile.readAsBytesSync();//
    String encodedFile = base64.encode(imageBytes);//this also gives same problem
log(encodedFile);  
......

Other Stuff
    
  }

截屏

在线转换工具以这些字符开头

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANcAAADXCAYAAACJfcS1AAA6BUlEQVR42u19B5QU1dbu3H/dtLw55/Svdd979/03vWtCVKKIiqCiKDmIJC9BEEYkM+Q85JyGOAzBITNkEAdUMiiCkpGcMwj71Xdg9z1dc6rqVHd1d3V31Vp7wcx0VzjnfLX3/nY4GXP3H6VUkJGTJ1KrJ/8mZFjFR2hN/TIpLcvrlqICTVlZr3Tc7mt85WKUWfLvYh66NqhOs3buoVRZY24lIxUeYmzerBCwcl4pnjIAAjAW1SpBCw2ZV/

标签: flutterflutter-dependenciesflutter-image

解决方案


我有同样的问题,我这样解决了

Future<String> tobase64(File image) async {
  // I encode files to base64 format
  List<int> imgBytes = await image.readAsBytes();
  String base64img = base64Encode(imgBytes);
  return base64img;
}


  Future getImage(
    ImageSource source,
  ) async {
    final pickedFile = await picker.getImage(source: source);

    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });

      List<String> _splitted = pickedFile.path.split('.');
// this is the  important line on formating
      _process("data:image/${_splitted.last};base64,");
    }
  }



// this method process and formats your base64 data to the standard format
 Future _process(String format) async {
    baseSix4 = format + await tobase64(_image);

  }

推荐阅读