gpt4 book ai didi

dart - 如何将 Assets 图像转换为文件?

转载 作者:IT王子 更新时间:2023-10-29 06:51:05 31 4
gpt4 key购买 nike

有没有办法将 Assets 图像用作文件。我需要一个文件,以便它可以用于使用 http 在 Internet 上对其进行测试。我尝试了 Stackoverflow.com (How to load images with 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'),)

使用 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'))),

最佳答案

您可以通过 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;
}

在您的示例中,您将像这样调用此函数:

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

有关写入字节数据的更多信息,check out this answer .

您需要await Future 并为此创建函数async:

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

关于dart - 如何将 Assets 图像转换为文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55295593/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com