How to convert Image to File in Flutter?

16,652

Solution 1

Special thanks to sami kanafani.

This is my solution (works perfectly for me):

import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

class ImageUtils {
  static Future<File> imageToFile({String imageName, String ext}) async {
    var bytes = await rootBundle.load('assets/$imageName.$ext');
    String tempPath = (await getTemporaryDirectory()).path;
    File file = File('$tempPath/profile.png');
    await file.writeAsBytes(
        bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
    return file;
  }
}


class AnotherClass {
    File imagePlaceHolder;
    _setPlaceHolder() async {
         this.imagePlaceHolder = await ImageUtils.imageToFile(
         imageName: "photo_placeholder", ext: "jpg");
    }

    ...
    Image.file(this.imagePlaceHolder),
}

Solution 2

I had the exact same issue, and used this guide: https://medium.com/@mrgulshanyadav/convert-image-url-to-file-format-in-flutter-10421bccfd18 (written by Gulshan Yadav)

Using these imports:

import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'dart:math'; 

And this function:

Future<File> urlToFile(String imageUrl) async {
// generate random number.
var rng = new Random();
// get temporary directory of device.
Directory tempDir = await getTemporaryDirectory();
// get temporary path from temporary directory.
String tempPath = tempDir.path;
// create a new file in temporary path with random file name.
File file = new File('$tempPath'+ (rng.nextInt(100)).toString() +'.png');
// call http.get method and pass imageUrl into it to get response.
http.Response response = await http.get(imageUrl);
// write bodyBytes received in response to file.
await file.writeAsBytes(response.bodyBytes);
// now return the file which is created with random name in 
// temporary directory and image bytes from response is written to // that file.
return file;
}
Share:
16,652
Jayant Jeet Tomar
Author by

Jayant Jeet Tomar

Coder Technophile Gamer Author by hobby.

Updated on June 12, 2022

Comments

  • Jayant Jeet Tomar
    Jayant Jeet Tomar almost 2 years

    I am writing this flutter code where I have Image in an Image widget and I want to convert it into File so that I can upload it to Firebase Storage.

    Image _image = Image.asset('assets\images\profile.png');
    File _fileImage = convertToFile(_image);
    //upload _fileImage to Firebase Storage code
    

    I need the File convertToFile(Image img) function.