Home > Back-end >  How I can capture image with camera and save in my phone storage flutter?
How I can capture image with camera and save in my phone storage flutter?

Time:05-30

I am able to capture image with camera but I can't save it my phone storage.Help me please.Thanks in advance.
UI part here:

 File? image;
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 300,
          width: 300,
          child: image != null
              ? Image.file(image!)
              : Container(
                  height: 300,
                  width: 300,
                  color: Colors.indigo,
                ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.grey[300],
        child: Icon(Icons.camera),
        onPressed: () {
          getImage();
        },
      ),
    );
  }

Logic part here: After clicking the floating action button getImage method will call. I show my code below. I am able to capture image but I can't save image in my phone storage. Please help me.

Future getImage() async {
    final XFile? pickedFile =
        await ImagePicker().pickImage(source: ImageSource.camera);
    try {
      if (pickedFile != null) {
        Directory appDocDir = await getApplicationDocumentsDirectory();
        String path = appDocDir.path;
         File pickedImageFile = File(pickedFile.path);
         final  _baseName = Path.basename(pickedFile!.path);
        final String _fileExtension = Path.extension(pickedFile.path);
        final File newImage = await pickedImageFile!.copy('$path/$_baseName$_fileExtension');
        setState(() {
          image = newImage;
          print("file path...");
        });
      } else {
        print('No image selected.');
      }
    } catch (e) {
      print(e);
    }
  } 

CodePudding user response:

First, Install Two plugins.
1.This plugin gallery_saver saves images and videos from the camera or network to local storage(both Android and iOS).
2.This plugin image_picker saves images and videos from the camera or network to local storage(both Android and iOS).

import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:image_picker/image_picker.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

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

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

  void _takePhoto() async {
    await _picker
        .pickImage(source: ImageSource.camera)
        .then((XFile? 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 {
    await _picker
        .pickVideo(source: ImageSource.camera)
        .then((XFile? recordedVideo) {
      if (recordedVideo != null && recordedVideo.path != null) {
        setState(() {
          secondButtonText = 'saving in progress...';
        });
        GallerySaver.saveVideo(recordedVideo.path).then((path) {
          setState(() {
            secondButtonText = 'video saved!';
          });
        });
      }
    });
  }
}

N.B: You must set your minSdkVersion to 21 (you have found your minSdkVersion inside \android\app\build.gradle).

CodePudding user response:

You can use image_gallery_saver package.

_saveImageToGallery(String path) async {
    final result = await ImageGallerySaver.saveFile(path);
    print(result);
 }

Remember to add the required permission to your manifest. you can find it on this package's readme page.

  • Related