如何将图像转换为字节,然后再次将其转换为颤动中的图像?

Anu*_*Anu 5 base64 image flutter

我正在尝试使用image_picker插件。我可以使用这个插件将图像作为文件获取。我需要将此图像转换为字节并发送到 api。所以我尝试使用 dart:convert 将图像转换为字节字符串。现在,当我解码时,我得到一个Uint8List类型。如何将其转换为文件并在Image.file()中显示。我无法\xe2\x80\x99t 从这里继续。有人可以帮我弄这个吗。

\n\n

考虑一下我从 api 响应中得到的已解码字节,我如何将它们转换为在图像小部件中显示

\n\n

这是我到目前为止尝试过的代码。

\n\n
var image = await ImagePicker.pickImage(source: ImageSource.camera);\n\n    setState(() {\n      imageURI = image;\n      final bytes = image.readAsBytesSync();\n\n      String img64 = base64Encode(bytes);\n      print(bytes);\n      print(img64);\n\n      final decodedBytes = base64Decode(img64);\n      print(decodedBytes);\n      //consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget \n    });\n
Run Code Online (Sandbox Code Playgroud)\n\n

我使用writeAsBytesSync()收到此错误,

\n\n
Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'\n
Run Code Online (Sandbox Code Playgroud)\n

her*_*ert 1

您会收到此错误,因为您无法写入应用程序沙箱中的任何任意位置。您可以使用path_provider查找临时目录。

但在你的情况下,只需使用该image对象,pickImage已经返回一个 File 对象,所以只需使用Image.file(image)

如果要将 Base64 解码到临时目录中,可以使用:

import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

Future<File> writeImageTemp(String base64Image, String imageName) async {
  final dir = await getTemporaryDirectory();
  await dir.create(recursive: true);
  final tempFile = File(path.join(dir.path, imageName));
  await tempFile.writeAsBytes(base64.decode(base64Image));
  return tempFile;
}
Run Code Online (Sandbox Code Playgroud)

使用 pubspec.yaml:

dependencies:
  path: ^1.6.0
  path_provider: ^1.6.7
Run Code Online (Sandbox Code Playgroud)