How to convert Image to File in Flutter?

匆匆过客 提交于 2021-02-07 20:10:55

问题


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:


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),
}



回答2:


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;




回答3:


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;
}


来源:https://stackoverflow.com/questions/62368886/how-to-convert-image-to-file-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!