How to convert an Image instance to File instance in Flutter?

1.8k Views Asked by At

I am using VideoThumbanil class to fetch an Uint8List image of a video like this:

final uint8List = await VideoThumbnail.thumbnailData(video: videoFile.path,);

After doing so, i am converting the Uint8LIST to an Image using the following code:

Image image = Image.memory(uint8List);

What I want to do is to convert this image to a File class instance so that I can upload this image to my server. Code for uploading on server is:

void asyncFileUpload(File file) async {
  //create multipart request for POST or PATCH method
  var request = http.MultipartRequest("POST", Uri.parse("127.0.0.1/upload"));
  //create multipart using filepath, string or bytes
  var pic = await http.MultipartFile.fromPath("image", file.path);
  //add multipart to request
  request.files.add(pic);
  var response = await request.send();
  //Get the response from the server
  var responseData = await response.stream.toBytes();
  var responseString = String.fromCharCodes(responseData);
  print(responseString);
}
3

There are 3 best solutions below

0
Abdul Ahad Akram On BEST ANSWER

You can fetch the path to the temporary directory:

final tempDir = await getTemporaryDirectory();

After doing so, you can create a File in that temporary directory:

File fileToBeUploaded = await File('${tempDir.path}/image.png').create();

This way your file has a path and it's instance has been created. Now, you can write the file as:

fileToBeUploaded.writeAsBytesSync(uint8List);

Now, you can use fileToBeUploaded as File that is actually an image.

Complete code:

final uint8List = await VideoThumbnail.thumbnailData(video: videoFile.path,);
final tempDir = await getTemporaryDirectory();
File fileToBeUploaded = await File('${tempDir.path}/image.png').create();
fileToBeUploaded.writeAsBytesSync(uint8List);
asyncFileUpload(fileToBeUploaded);
2
Kaushik Chandru On

Since you already have the uint8 list you can try

File fileTpSend = File.fromRawPath(Uint8List uint8List);
0
Andrii Kovalchuk On

Based on your code you need to import 'dart:io' and user fromRawPath function from File class (check snippet below)

import 'dart:io';

final uint8List = await VideoThumbnail.thumbnailData(video:videoFile.path);
final imageAsFile = File.fromRawPath(uint8List);
await asyncFileUpload(imageAsFile);

But this method doesn't work for Flutter WEB