Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Image to File in Flutter?

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.

like image 734
Jayant Jeet Tomar Avatar asked Jun 14 '20 05:06

Jayant Jeet Tomar


2 Answers

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),
}
like image 154
Andres Paladines Avatar answered Oct 07 '22 02:10

Andres Paladines


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;
}
like image 34
Jon Avatar answered Oct 07 '22 01:10

Jon