6

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.

1
  • @Uni I'm not picking image from photos or camera. It's present in the assets folder. Commented Jun 14, 2020 at 7:05

3 Answers 3

9

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),
}
Sign up to request clarification or add additional context in comments.

3 Comments

What is this part of your code doing? String tempPath = (await getTemporaryDirectory()).path; File file = File('$tempPath/profile.png'); await file.writeAsBytes( bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));
Is the path where you will put the file (profile.png) and the bytes.buffer.asUint8List(.. is the responsible to write the "in memory file" to the device.
Hello @JavierHeisecke, this line: (await getTemporaryDirectory()).path only gets the temporary path directory inside app, File creates an empty file and file.writeAsBytes just get the data bytes provided previously and save them in the empty file.
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;
}

Comments

1

You need to convert the asset not the image

You need to install path_provider plugin


  var bytes = await rootBundle.load('assets\images\profile.png');
  String tempPath = (await getTemporaryDirectory()).path;
  File file = File('$tempPath/profile.png');
  await file.writeAsBytes(bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));

  return file;

4 Comments

Does not work. Throws this error. [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.xyz/cache/images/profile.png' (OS Error: No such file or directory, errno = 2)
try to replace the \ with /
Getting this error. It is returning null. The following assertion was thrown building UserSignUpScreen(dirty, state: _UserSignUpScreenState#e96f8): 'package:flutter/src/painting/image_provider.dart': Failed assertion: line 826 pos 14: 'file != null': is not true.
found the issue, remove the /image from the file constructor, i edited the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.