如何解决Flutter:图像base64编码|扑中base64编码的字节不准确
我正尝试使用图像裁剪器和选择器库将图像上传到服务器。它工作正常,但是在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/
解决方法
我遇到了同样的问题,我这样解决了
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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。