John Joe
John Joe

Reputation: 12803

How to convert Image to File?

What is the correct way to save Image to device where the image is not taken from gallery or camera?

In PageA, there is a camera button allow user to capture image. Once image is captured, it will go to PageB (EditImagePage). Once user done editing the image, it will back to PageA, and save the image to device.

PageA

  @override
  userImage(File images) async {  // when user has captured image, it will run this code
    if (images != null) {
      Image image = await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => EditImagePage(images.path), // go to edit image page
          ));
         // convert image to File
         // call copyImage function
    } else {

    }
  }

PageB

 IconButton(
          icon: Icon(Icons.check),
          onPressed: () async {
            Uint8List bytes = await _controller.exportAsPNGBytes();
            var image = Image.memory(bytes);
            return Navigator.pop(context, image);  // bring Image back to PageA
          }),

I have this code used to save the Image to device. How can change it to File?

Future<File> copyImage(File image) async {
        var savedDir = await getApplicationDocumentsDirectory();
        String appDocPath = savedDir.path;
        var fileName = FileUtils.basename(image.path);
        return await image.copy('$appDocPath/' + '$fileName');
      }

Upvotes: 4

Views: 6504

Answers (1)

Rohit Soni
Rohit Soni

Reputation: 1447

You can store image to device internal storage, convert image, assets image to File and store into device storage.

First of get your image path, make to file and writeAsBytes for image.

You can write code as below :

import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart' show rootServices;
import 'package:path_provider/path_provider.dart';

Future<File> convertImageToFile(String imagePath) async {
  final byteData = await rootServices.load('assets/$imagePath');

  final file = File('${(await getTemporaryDirectory()).path}/$imagePath');
  await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}

Need to storage access permission, don't forgot it.

Upvotes: 2

Related Questions