如何将资产图片转换为文件? [英] How to convert asset image to File?

查看:76
本文介绍了如何将资产图片转换为文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将资产图片用作文件。
我需要一个文件,以便可以使用http在Internet上对其进行测试。我已经尝试过Stackoverflow.com(如何使用图像加载图像的一些答案。文件),但显示错误无法打开文件,(操作系统错误:无此类文件或目录,错误号= 2)。

Is there a way to use an asset image as a File. I need a File so it can be used for testing it over the internet using http. I've tried some answers from Stackoverflow.com (How to load images with image.file) but get an error 'Cannot open file, (OS Error: No such file or directory, errno = 2)'. The attached code line also gives an error.

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

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

使用Image.memory小部件(作品)

Using Image.memory widget(works)

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 (您需要将其添加为依赖项)。

You can access the byte data via rootBundle. Then, you can save it to the device's temporary directory which is obtained by path_provider (you need to add it as a dependency).

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;
}

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

In your example, you would call this function like this:

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

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

For more information on writing the byte data, check out this answer.

您需要等待 Future 并为了做到这一点,使函数 async

You will need to await the Future and in order to do that, make the function async:

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

这篇关于如何将资产图片转换为文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆