Convert File to Image

Viewed 2057

I take a picture using ImagePicker that is saved like File. What I want is to convert it to png before upload it to FirebaseStorage. The problem is that when I try to convert it using this function:

File('test.png').writeAsBytesSync(encodePng(image));

it gave me error because the photo is saved like File not Image. I've googled for some type of plugin or function to convert it from File to Image but have found nothing concrete. Can anyone help me with this, please?

EDIT: Just to be sure I explained it clearly: I have photo 'photo 1.jpeg' that is stored like File, because this is what the ImagePicker does. Then I want to convert this File to Image and then convert it to .png

3 Answers

If you want to re-encode your image as a PNG, you will need to:

  1. Read the bytes from the file via File.readAsBytes. This will give you a Uint8List (which is compatible with List<int>).
  2. You then will need to decode those bytes (e.g. with decodeJpg) to transform them into package:image's Image type.
  3. Next you will need to use encodePng on the Image. This will give you more bytes (as a List<int>).
  4. Finally you will need to write those bytes to a file via File.writeAsBytes.

All that said, it's rather pointless to decode a JPEG and to re-encode it as a PNG; you're just making the image take up more space than it needs to.

Use this function:

Future<Image> convertFileToImage(File picture) async {
  List<int> imageBase64 = picture.readAsBytesSync();
  String imageAsString = base64Encode(imageBase64);
  Uint8List uint8list = base64.decode(imageAsString);
  Image image = Image.memory(uint8list);
  return image;
}

It takes picture in the File format and returns back the image in Image format.

Don't forget to add await while calling the function.

Here is how you would get the encoded path for the file.

File file = File('test.png);
String encodedImagePath = base64Encode(await file.readAsBytes());
Related