【问题标题】:Flutter: image base64 encode | bytes to base64 encode in flutter is not accurateFlutter:图像 base64 编码 |颤振中base64编码的字节不准确
【发布时间】:2021-02-23 10:04:15
【问题描述】:

我正在尝试将图像上传到服务器,顺便说一下,我使用了 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/

【问题讨论】:

    标签: flutter flutter-dependencies flutter-image


    【解决方案1】:

    我遇到了同样的问题,我是这样解决的

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

    【讨论】:

    • 侧面结果相同,变化在于您的代码连接了前面的“data:image/jpg;base64”文本,但其他文本看起来与我之前得到的相同,
    • 不仅是前面,还要在'data:image/'和';base64,'之间插入图片数据
    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多