Attila
Attila

Reputation: 63

I want to save Image from ImagePicker to SharedPreferences - Flutter

I have this piece of code. I want to store the image that the user picked from the gallery or took by camera (ImagePicker) to SharedPreferences, but I don't know how to do it.

File? image;

  Future pickImage() async {
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);
      if (image == null) return;

      final imagePermenant = await saveImagePermenantly(image.path);
      setState(() {
        this.image = imagePermenant;
      });
    } on PlatformException catch (e) {
      print("Failed to pick image:$e");
    }
  }

  Future takePhoto() async {
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.camera);
      if (image == null) return;

      final imagePermenant = await saveImagePermenantly(image.path);
      setState(() {
        this.image = imagePermenant;
      });
    } on PlatformException catch (e) {
      print("Failed to take photo:$e");
    }
  }

  Future<File> saveImagePermenantly(String imagePath) async {
    final directory = await getApplicationDocumentsDirectory();
    final name = basename(imagePath);
    final image = File("${directory.path}/$name");

    return File(imagePath).copy(image.path);
  }

Upvotes: 0

Views: 181

Answers (1)

pmatatias
pmatatias

Reputation: 4404

Why do you save images into sharedpreferences. as documentation said, it only support to save String, int, bool [here].

but if you want to try, you can convert your image to String (base64) and save it. but it will be a very long String.

final SharedPreferences prefs = await SharedPreferences.getInstance();
 // convert your image to base64.
 String base64Image = base64Encode(imageBytes);
 // store the image
 prefs.setString("image", base64Image);

Upvotes: 1

Related Questions