4
votes

flutter comment enregistrer une image de l'appareil photo sur l'appareil?

J'essaie d'enregistrer une photo de la caméra sur un appareil réel, mais je ne trouve pas de moyen.

À l'heure actuelle, je l'ai enregistré dans un fichier, mais je ne peux pas l'obtenir dans la galerie.

Mon code pour le moment est:

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


0 commentaires

6 Réponses :



3
votes

Je viens d'écrire album_saver pour ce plugin

Cela peut fonctionner sur les deux IOS et 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();


1 commentaires

@MuhammadFaizan Oui, cela fonctionnera avec ImageSource.camera



5
votes

Ce plugin https://pub.dev/packages/gallery_saver enregistre les images et les vidéos de la caméra ou du réseau vers le stockage local (Android et iOS)

Voici comment il est utilisé:

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

chemin est le chemin local ou l'URL du réseau.

Il renvoie Future - vrai s'il a été enregistré avec succès et faux s'il ne l'a pas été (pour une raison quelconque).


1 commentaires

C'était de loin la solution la plus simple pour moi, merci - fonctionne sur mon téléphone Android



0
votes

* Ma solution à ce problème est SharedPreferences - stockez FileName.path en tant que chaîne et restaurez dans File (chemin); peut-être que cela aidera quelqu'un *

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


0 commentaires

2
votes

J'ai essayé beaucoup de plugins de flutter pour enregistrer l'image, et seul celui-ci fonctionne. Gallery_saver v1.0.7

Mais l'exemple contient une petite erreur qui explique pourquoi je n'ai pas pu exécuter. Voici l'exemple correct:

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 commentaires

0
votes

pickImage est obsolète. Vous devez utiliser ImagePicker.getImage ().

Plus d'informations

 entrez la description de l'image ici

Utilisez le code ci-dessous pour stocker la photo de l'appareil photo ou de la galerie.

//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 commentaires