【问题标题】:how to convert image to byte and again convert it to image in flutter?如何将图像转换为字节并再次将其转换为颤动的图像?
【发布时间】:2020-08-13 16:26:36
【问题描述】:

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

考虑到我从 api 响应中得到这个 decodedBytes,我如何将它们转换为在 Image 小部件中显示

这是我目前尝试的代码。

var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      imageURI = image;
      final bytes = image.readAsBytesSync();

      String img64 = base64Encode(bytes);
      print(bytes);
      print(img64);

      final decodedBytes = base64Decode(img64);
      print(decodedBytes);
      //consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget 
    });

我在使用 writeAsBytesSync() 时遇到此错误,

Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'

【问题讨论】:

    标签: image flutter base64


    【解决方案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;
    }
    

    使用 pubspec.yaml:

    dependencies:
      path: ^1.6.0
      path_provider: ^1.6.7
    

    【讨论】:

    • 我将从 api 获取 base64 字符串,我需要将它们转换为某种格式并显示在 Imgae 小部件中。怎么做? @赫伯特
    • @Anu 用 base64.decode() 解码,在临时目录下创建一个文件(如果你每次都下载新的,否则在documents目录下),写..你就完成了..例如` final tempDir = await getTemporaryDirectory(); tempDir.create(recursive: true);final file = File(path.join(tempDir.path, 'tmp.png')); await file.writeBytes(bytes);
    • getTemporaryDirectory from pub.dev/packages/path_provider -- path.join 使用:import 'package:path/path.dart' as path; pub.dev/packages/path
    • 您能否在答案中添加代码片段? @赫伯特
    • @Anu 我添加了一个示例,如何将 base64 转换为二进制图像并返回一个可以与Image.file 一起使用的临时文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多