如何在Flutter中将图像从路径转换为Base64?

时间:2020-02-06 02:13:43

标签: flutter base64

我试图捕获图像,然后将图像的路径发送到在Base64中返回图像的函数。为了捕获图像,我使用Flutter网站上的示例。

Future _takePhoto(BuildContext context) async {
  try {
    await _initializeControllerFuture;

    final path = join(
      (await getTemporaryDirectory()).path,
      '${DateTime.now()}.png',
    );

    await _cameraController.takePicture(path);

    setState(() {
      _imagePath = path;
    });

  } catch (e) {
    print(e);
  }
}

运行良好。我可以在小部件Image.file(File(_imagePath))

中看到捕获的图像

当我尝试将图像转换为Base64时,问题开始了。

File file = File(_imagePath);
final _imageFile = ImageProcess.decodeImage(
  file.readAsBytesSync(),
);

String base64Image = base64Encode(ImageProcess.encodePng(_imageFile));
print(base64Image);

我将打印的消息复制并粘贴到一个在线工具中,该工具从Base64生成图像,该图像是全黑的,或者图像的顶层很小,其余的是黑色的。

3 个答案:

答案 0 :(得分:1)

print功能无法打印所有内容。
您可以在调试模式下查看完整结果
并将全部结果以调试模式复制并粘贴到在线工具

enter image description here

enter image description here

答案 1 :(得分:0)

这应该将图像打印为base64字符串

import 'dart:typed_data';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
File file = File(_imagePath);
Uint8List bytes = file.readAsBytesSync();
String base64Image = base64Encode(bytes);
print(base64Image);

答案 2 :(得分:0)

要显示 base64 打印:

导入 'dart:developer' 作为开发者;

developer.log(
      'log me',
      name: 'my.app.category',
      error: jsonEncode(base64Image),
    );