'How to convert CameraController's XFile to Image type in Flutter?
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?
Solution 1:[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:[2]
You can get the path from XFlie by using .path property and then show image using
Container(
child: Image.file(File(XFile.path)),
);
Solution 3:[3]
Two different solutions than the answers adopted:
Use cross_file_image dependency.
import 'package:cross_file_image/cross_file_image.dart'; Image(image: XFileImage(xfile));
Call
readAsBytes
method.import 'dart:typed_data'; import 'package:flutter/cupertino.dart'; import 'package:cross_file/cross_file.dart'; Future<Image> xFileToImage(XFile xFile) async { final Uint8List bytes = await xFile.readAsBytes(); return Image.memory(bytes).image; }
Image(image: await xFileToImage(xFile));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mohsen Emami |
Solution 2 | Ali Hassan |
Solution 3 | Terry |