简体   繁体   English

Flutter:图像 base64 编码 | 在颤振中对 base64 编码的字节不准确

[英]Flutter: image base64 encode | bytes to base64 encode in flutter is not accurate

I am Trying to Upload a image to server, by the way I have used Image Cropper and Picker Libraries.我正在尝试将图像上传到服务器,顺便说一下,我使用了 Image Cropper 和 Picker 库。 it works fine, but during API Call I need to encode as base64, here the encoded string is wrong comparing to online image-to-base64 encode tool.它工作正常,但在 API 调用期间我需要编码为 base64,这里的编码字符串与在线图像到 base64 编码工具相比是错误的。 so Server Failed to Save the data even if it Saved it seems Invalid Image.所以服务器无法保存数据,即使它保存了它看起来无效的图像。 Please Help me to resolve this problem.请帮我解决这个问题。

I have checked in API using Postman (online base64 image tools), it works fine.我已经使用 Postman(在线 base64 图像工具)检查了 API,它工作正常。

Code :代码 :

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
    
  }

截屏

Online Convert Tool Starts With these Characters在线转换工具以这些字符开头

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

i have had the same issue and i resolved it like this我有同样的问题,我是这样解决的

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

  }

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

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