如何将资产图像转换为文件?

Ant*_*t D 25 dart flutter

有没有办法将资产图像用作文件。我需要一个文件,以便它可以用于使用 http 在 Internet 上进行测试。我已经尝试了 Stackoverflow.com 的一些答案(如何使用 image.file 加载图像)但收到错误“无法打开文件,(操作系统错误:没有这样的文件或目录,errno = 2)”。附加的代码行也给出了错误。

File f = File('images/myImage.jpg');

RaisedButton(
   onPressed: ()=> showDialog(
     context: context,
     builder: (_) => Container(child: Image.file(f),)),
   child: Text('Show Image'),)
Run Code Online (Sandbox Code Playgroud)

使用 Image.memory 小部件(有效)

Future<Null> myGetByte() async {
    _byteData = await rootBundle.load('images/myImage.jpg');
  }

  /// called inside build function
  Future<File> fileByte = myGetByte();

 /// Show Image
 Container(child: fileByte != null
 ? Image.memory(_byteData.buffer.asUint8List(_byteData.offsetInBytes, _ 
 byteData.lengthInBytes))
 : Text('No Image File'))),
Run Code Online (Sandbox Code Playgroud)

cre*_*not 35

您可以通过访问字节数据rootBundle。然后,您可以将其保存到通过path_provider(需要将其添加为依赖项)获取的设备的临时目录中。

import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';

Future<File> getImageFileFromAssets(String path) async {
  final byteData = await rootBundle.load('assets/$path');

  final file = File('${(await getTemporaryDirectory()).path}/$path');
  await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您可以这样调用此函数:

File f = await getImageFileFromAssets('images/myImage.jpg');
Run Code Online (Sandbox Code Playgroud)

有关写入字节数据的更多信息,请查看此答案

您需要awaitFuture,为了做到这一点,使功能async

RaisedButton(
   onPressed: () async => showDialog(
     context: context,
     builder: (_) => Container(child: Image.file(await getImageFileFromAssets('images/myImage.jpg')))),
   child: Text('Show Image'));
Run Code Online (Sandbox Code Playgroud)

  • 我在创建文件后添加了“await file.create(recursive: true);”。因为如果您的路径包含尚不存在的目录,则写入该文件会失败,因为默认情况下 create 的递归值为 false。 (5认同)
  • @ creativecreatorormaybenot 现在它确实有效。我遇到的问题是函数“getImageFileFromAssets”在 getTemporaryDirectory() 中添加了“images/myImage.jpg”,而不仅仅是“/myImage.jpg”。我终于有文件了!谢谢。 (4认同)
  • 您好,我遵循解决方案,但收到有关未处理异常的错误:FileSystemException:无法打开文件,路径='/data/user/0/com.example.myApp/cache/images/black.png'(操作系统错误:否)这样的文件或目录,errno = 2) (4认同)
  • @creativecreatorormaybenot我认为你应该用`final file = File('${(await getTemporaryDirectory()).path}/$path');`替换`final file = File('${(await getTemporaryDirectory()).path }/image.png');` 这将为未来的商业者节省时间 (3认同)