代码之家  ›  专栏  ›  技术社区  ›  Ravindra Bhanderi

如何保存颤振中的图像文件?使用图像选取器插件选择的文件

  •  3
  • Ravindra Bhanderi  · 技术社区  · 8 年前

    我真的很困惑。颤振是可怕的,但有一段时间是卡在心里的。

    所有代码都完成了。选定的文件也显示在预览中,但我尝试将该文件保存在本地Android存储中。我不能成功

      Future getImage(ImageSource imageSource) async {
        var image = await ImagePicker.pickImage(source: imageSource);
    
        setState(() {
          _image = image;
        });
      } 
    

    选择使用此代码的文件和我的文件 _image 现在我尝试使用路径提供程序和 dart.io 但是我不能得到保存方法。

    2 回复  |  直到 7 年前
        1
  •  7
  •   creativecreatorormaybenot    8 年前

    使用 await ImagePicker.pickImage(...) ,因为函数返回 File .

    这个 文件 类有一个 copy method ,您可以使用它复制文件(该文件已通过相机或放在图库中保存在磁盘上),并将其放入应用程序文档目录:

    // using your method of getting an image
    final File image = await ImagePicker.pickImage(source: imageSource);
    
    // getting a directory path for saving
    final String path = await getApplicationDocumentsDirectory().path;
    
    // copy the file to a new path
    final File newImage = await image.copy('$path/image1.png');
    
    setState(() {
      _image = newImage;
    });
    

    您还应该注意,您可以从 ImagePicker 使用 image.path ,它还将包含您可能要提取的文件结尾,您可以使用 newImage.path .

        2
  •  2
  •   Vivek Bansal    7 年前

    @CreativeCreatorNormaybonot答案确实很有帮助,但它遗漏了一个重要的部分,即检索图像供以后使用。

    保存图像

    // Step 1: Retrieve image from picker 
    final File image = await ImagePicker.pickImage(source: imageSource);
    
    // Step 2: Check for valid file
    if (image == null) return;
    
    // Step 3: Get directory where we can duplicate selected file.
    final String path = await getApplicationDocumentsDirectory().path;
    
    // Step 4: Copy the file to a application document directory. 
    final var fileName = basename(file.path);
    final File localImage = await image.copy('$path/$fileName');
    

    提示:您可以检索 文件名 从原始文件使用 basename(文件.path) . 确保导入“package:path/path.dart”;

    检索/加载图像

    // Step 1: Save image/file path as string either db or shared pref
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('test_image', localImage.path)
    
    // Step 2: Loading image by using the path that we saved earlier. We can create a file using path 
    //         and can use FileImage provider for loading image from file.
    CircleAvatar(
              backgroundImage: FileImage(File(prefs.getString('test_image')),
              radius: 50,
              backgroundColor: Colors.white)