flutter - 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/
解决方案
我有同样的问题,我这样解决了
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);
}
推荐阅读
- r - 使用西班牙语字符(á、é、í、ó、ú、ñ 等)将 .sql 读入 R
- jupyter-notebook - 如何在 haproxy 后面运行 jupyter notebook 并公开其内容?
- javascript - 如何打开带有标签的日期选择器不使用触发器?
- c# - 在 C# 中进行并行调用 - 如何识别哪个调用失败
- django-rest-framework - Django Rest 框架错误 HTTP 405 方法不允许方法 GET
- google-api - 谷歌日历,获取活动天数
- node.js - Spotify API 授权重定向太多次
- python - 如何使用并行编程更快地运行 scipy 的 ndimage.generic_filter()?
- jquery - 使用 textarea 将 html 插入数据库的严重问题
- firebase - Xamarin Firebase 和 Syncfusion DataGrid。如何监听 Firebase 更改?