Flutter如何将相机拍摄的照片保存到设备中?

8

我正在尝试从真实设备中保存照片,但找不到方法。

目前已经将它保存在了一个文件中,但无法在相册中找到它。

我目前的代码如下:

File _imagenTemporal;

String _opcion = "";

var imagen; 

Future getImagen(String opcion) async {

  if (opcion == "camara") {

    imagen = await ImagePicker.pickImage(source: ImageSource.camera);

  } else if (opcion == "galeria") {

    imagen = await ImagePicker.pickImage(source: ImageSource.gallery);

  }

  setState(() {
    _imagenTemporal = imagen;
  });
}
6个回答

11

这个插件https://pub.dev/packages/gallery_saver可以将摄像头或网络中的图片和视频保存到本地存储(支持Android和iOS)。

以下是使用方法:

GallerySaver.saveVideo(path)
GallerySaver.saveImage(path)

路径可以是本地路径或网络地址。

该函数返回Future类型,如果保存成功则返回true,如果由于任何原因保存失败则返回false。


2
这对我来说是迄今为止最简单的解决方案,谢谢 - 在我的安卓手机上运行。 - Cold_Class

8

您可以使用谷歌的路径提供程序插件将拍摄的图像持久化:

  • Path to local storage:

    directory = getApplicationDocumentsDirectory() // AppData folder path
    
    directory = getExternalStorageDirectory() // main storage folders path,but only works on android as IOS is not currently supported.
    
    path = directory.path ;
    
  • Copy imagen file to the path you got in the previous step using copy fuction:

    File savedImage = await imagen.copy('$path/saved_image.jpg');
    

这种方法存储的图像可以通过你的文件应用程序进行访问,并在你的图库照片应用程序中根据平台进行索引。您可以在官方菜谱读写文件路径提供者API文档上找到更多信息。


1
然后使用 getApplicationDocumentsDirectory(),但是您必须测试图像是否会出现在您的 Photos 应用程序中。 - Mazin Ibrahim

5

我刚刚为这个写了一个相册保存器插件

它可以在IOS和Android上工作。

import 'package:album_saver/album_saver.dart';
import 'package:image_picker/image_picker.dart';

File image = await ImagePicker.pickImage(source: ImageSource.gallery);

// Save to ablum
AlbumSaver.saveToAlbum(filePath: image.path, albumName: "YourAlbumName");

// Create album
// In Android, it will create a folder in DCIM folder
AlbumSaver.createAlbum(albumName: "YourAlbumName");

// Get DCIM folder path (just work on Android)
AlbumSaver.getDcimPath();

@MuhammadFaizan 是的,它可以与 ImageSource.camera 一起使用。 - Thắng Mai
你如何更改图像名称? - Mohammed H. Hannoush

2
我尝试了许多Flutter插件来保存图像,只有这个插件有效。 Gallery_saver v1.0.7 但是示例代码存在一些小错误,因此我无法运行它。以下是正确的示例代码:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String firstButtonText = 'Take photo';
  String secondButtonText = 'Record video';
  double textSize = 20;

  @override
 Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      body: Container(
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Container(
                child: SizedBox.expand(
                      child: RaisedButton(
                color: Colors.blue,
                onPressed: _takePhoto,
                child: Text(firstButtonText,
                    style:
                        TextStyle(fontSize: textSize, color: Colors.white)),
              ),
            ),
          ),
        ),
        Flexible(
          child: Container(
              child: SizedBox.expand(
            child: RaisedButton(
              color: Colors.white,
              onPressed: _recordVideo,
              child: Text(secondButtonText,
                  style: TextStyle(
                      fontSize: textSize, color: Colors.blueGrey)),
            ),
          )),
          flex: 1,
        )
      ],
    ),
  ),
));
  }

  void _takePhoto() async {
    ImagePicker.pickImage(source: ImageSource.camera).then((File recordedImage) {
  if (recordedImage != null && recordedImage.path != null) {
    setState(() {
      firstButtonText = 'saving in progress...';
    });
    GallerySaver.saveImage(recordedImage.path).then((path) {
      setState(() {
        firstButtonText = 'image saved!';
      });
    });
  }
});
  }

  void _recordVideo() async {
    ImagePicker.pickVideo(source: ImageSource.camera)
        .then((File recordedVideo) {
      if (recordedVideo != null && recordedVideo.path != null) {
        setState(() {
          secondButtonText = 'saving in progress...';
        });
        GallerySaver.saveVideo(recordedVideo.path).then((path) {
          setState(() {
            secondButtonText = 'video saved!';
          });
        });
      }
    });
  }
}

0

pickImage已被弃用,您应该使用ImagePicker.getImage()。

更多信息

enter image description here

使用以下代码从相机或图库中存储照片。

//getImage(ImageSource.camera) or getImage(ImageSource.gallery)

void getImage(ImageSource imageSource) async {
    PickedFile imageFile = await picker.getImage(source: imageSource);
    if (imageFile == null) return;
    File tmpFile = File(imageFile.path);
    final appDir = await getApplicationDocumentsDirectory();
    final fileName = basename(imageFile.path);
    localFile = await tmpFile.copy('${appDir.path}/$fileName');
    setState(() {
      _image = localFile;
    
    });
  }


0

*我对这个问题的解决方案是使用SharedPreferences - 将FileName.path存储为字符串,并还原为File(path); 也许这对某些人有帮助*

 //global variables:
  File imageFile;
  String finalPath;

  //store string value
  Future<void> storeSharedPrefs(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);
  }

  //restore string value
  Future<String> restoreSharedPrefs(String key, String inputValue) async {
    final prefs = await SharedPreferences.getInstance();
    final value = prefs.getString(key);

    if (value == null) {
      return null;
    }

    setState(() {
      inputValue = value;
    });

    return inputValue;
  }

  //load saves
  void loadPrefs() async {
    try {
      //restore saved shared prefs:
      finalPath = await restoreSharedPrefs('image', finalPath);

      //load imageFile with restored shared prefs path:
      this.setState(() {
        if (finalPath != null) imageFile = File(finalPath);
      });
      debugPrint('restored path is: $finalPath');
    } catch (e) {
      print('loading error: $e');
    }
  }

  @override
  void initState() {
    super.initState();
    loadPrefs();
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接