如何将图片从素材资源保存到内部存储中?

时间:2020-08-06 02:49:55

标签: image file flutter dart

我正在尝试将图像从资产保存到内部存储。但是,我无法将图像从资产加载到文件。这是我所做的:

onTap: () async {
  
  final String documentPath = (await getApplicationDocumentsDirectory()).path;
  String imgPath = (galleryItems[currentIndex].assetName).substring(7);
  File image = await getImageFileFromAssets(imgPath);

  print(image.path);
}

我使用substring(7)来消除assets/,因为我的assetName是assets/images/foo.jpg

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

  final file =
      await File('${(await getApplicationDocumentsDirectory()).path}/$path')
          .create(recursive: true);
  await file.writeAsBytes(byteData.buffer
      .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}

获取image之后,我不知道如何继续在内部存储中创建一个使用我的名字的目录。然后,在此处复制文件。

*注意:-由于指出了一些基本错误,我对帖子进行了编辑。

更新

这是我想出的。并将图像保存在/storage/emulated/0/Android/data/com.example.my_project/files/Pics/foo.jpg路径中。

File image = await getImageFileFromAssets(imgPath);

final extDir = await getExternalStorageDirectory();

// Path of file
final myImagePath = '${extDir.path}/Pics';

// Create directory inside where file will be saved
await new Directory(myImagePath).create();

// File copied to ext directory.
File newImage =
    await image.copy("$myImagePath/${basename(imgPath)}");

print(newImage.path);

以下一些链接确实对我有帮助:

特别感谢@David的帮助。如果您要解决类似的问题,请查看评论以了解整个场景。

所以,我接受@David的回答。

2 个答案:

答案 0 :(得分:1)

您正在尝试在不存在的路径中创建文件对象。您正在使用资产路径,即相对于Flutter项目根目录的路径。但是,该路径在设备的documents文件夹中不存在,因此无法在此处创建文件。该文件在资产文件夹中也不存在,因为您正在添加文档路径。

要解决您的问题,应将assetName传递到rootBundle.load(),不要使用文档路径,并在File()之类的地方打开$documentPath/foo.jpg

编辑: 要创建文件,您仍然必须调用File.create,因此您需要运行:

final file = await File('$documentPath/images/foo.jpg').create(recursive: true);

答案 1 :(得分:1)

为了以后参考,这只是为了更新@Biplove的解决方案,它对我这个新手帮助很大......

Future<File> getImageFileFromAssets(String unique, String filename) async {
  ByteData byteData = await rootBundle.load(assets/filename));

  // this creates the file image
  File file = await File('$imagesAppDirectory/$filename').create(recursive: true); 

  // copies data byte by byte
  await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
  
  return file;
}

谢谢。