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

How to convert image from path to Base64 in flutter?

我正在尝试捕获图像,然后将图像的路径发送到 returns 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 生成图像,要么全黑,要么图像的顶层很小,其余部分是黑色。

print 函数没有打印所有内容。
你可以在调试模式下看到完整的结果
并将调试模式下的完整结果复制粘贴到在线工具

这应该将您的图像打印为 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);

要显示 base64 打印:

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

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