How to convert CameraController's XFile to Image type in Flutter?

7,696

Solution 1

This is my found solution:

import 'dart:io';
import 'package:image/image.dart' as img;

...

CameraController _controller;

...

final xFile = await _controller.takePicture();
final path = xFile.path;
final bytes = await File(path).readAsBytes();
final img.Image image = img.decodeImage(bytes);

Solution 2

You can get the path from XFlie by using .path property and then show image using

Container(
  child: Image.file(File(XFile.path)),
);
Share:
7,696
Mohsen Emami
Author by

Mohsen Emami

It’s 10 years that I've been working in software development industry with the concentration on developing Native and Cross-Platform applications using Android (Java/Kotlin) and also Flutter framework (Dart). I'm an ever-learning process-focused mobile engineer that always enjoyed working with new technologies and being challenged with obstacles to overcome. I've master's degree in Computer Engineering from University of Tehran and have always tried to apply my academic knowledge in my professional work.

Updated on December 27, 2022

Comments

  • Mohsen Emami
    Mohsen Emami over 1 year

    Flutter's CameraController has a takePicture() method for taking picture from the camera which gives type of Future<XFile>, so I need to convert it to Image type from package:image/image.dart package to manually crop it with another method.

    How to convert it?

  • Sevastyan Savanyuk
    Sevastyan Savanyuk over 2 years
    No need to create a File: final bytes = await file.readAsBytes(); return decodeImage(bytes);
  • Kohls
    Kohls almost 2 years
    OP asked for Image type, not presenting Image path in Widget
  • data_pikachu
    data_pikachu almost 2 years
    The argument type 'Future<Uint8List>' can't be assigned to the parameter type 'List<int>' - I get this error using this method