flutter how save a picture from camera to device?
Asked Answered
S

6

8

I'm trying to save a picture from camera in a real device, but can't find a way.

By now I get it saved in a File, but can't get it in the gallery..

My code at this moment is:

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;
  });
}
Sarisarid answered 8/3, 2019 at 7:47 Comment(0)
A
11

This plugin https://pub.dev/packages/gallery_saver saves images and videos from camera or network to local storage(both Android and iOS)

This is how it's used:

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

path is local path or network url.

It returns Future - true if it was saved successfully and false if it wasn't(for any reason).

Academe answered 8/8, 2019 at 14:13 Comment(1)
This was by far the easiest solution for me, thx - works on my android phoneTeodoor
R
8

You can persist the Image taken using the google's path provider plugin:

  • 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');
    

These Images stored by this methodology can be accessed using your Files application and indexed in your Gallery or Photos app depending on the platform.You can find more information on official cookbook read and write files and path provider API documentation.

Rox answered 8/3, 2019 at 9:32 Comment(1)
Then use the getApplicationDocumentsDirectory(), but you have to test whether the image will appear in your Photos app.Rox
P
5

I've just written album_saver plugin for this

This can work on both IOS and 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();
Pullman answered 13/4, 2019 at 14:9 Comment(2)
@MuhammadFaizan Yes, It will work with ImageSource.cameraMaharanee
How could you change image name?Kentiggerma
A
2

I tried a lot of flutter plugins to save image, and only this one works. Gallery_saver v1.0.7

But the example has a little error thats why i wasn't able to run it. Here's the correct example:

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!';
          });
        });
      }
    });
  }
}
Astor answered 31/3, 2020 at 10:28 Comment(0)
E
0

*My solution for this problem is SharedPreferences - store FileName.path as a String and restore to File(path); maybe this will help for someone *

 //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();
  }
Exposed answered 1/1, 2020 at 21:22 Comment(0)
D
0

pickImage is deprecated. You should use ImagePicker.getImage().

More Information

enter image description here

Use below code to store the photo from camera or gallery.


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

Dorie answered 20/10, 2020 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.