To convert a CameraImage stream into bytes or a file in Flutter, you can use the following steps:
import 'dart:typed_data';
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;
Uint8List imageToByte(CameraImage image) {
final int width = image.width;
final int height = image.height;
final Uint8List bytes = Uint8List(image.planes[0].bytes.length);
for (int plane = 0; plane < image.planes.length; plane++) {
bytes.setRange(
plane == 0 ? 0 : bytes.length - image.planes[plane].bytes.length,
bytes.length,
image.planes[plane].bytes);
}
// Prepare the image for conversion to png.
img.Image imgCamera = img.Image.fromBytes(width, height, bytes);
img.Image img1 = img.copyRotate(imgCamera, -90); //rotate -90 degree
// Convert to png.
Uint8List pngBytes = Uint8List.fromList(img.encodePng(img1));
return pngBytes;
}
StreamBuilder(
stream: controller?.imageStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
final image = snapshot.data;
final bytes = imageToByte(image);
// Now you can use the bytes however you want
// For example, to save the byte as a file:
final file = File('example.png');
file.writeAsBytesSync(bytes);
// Or, to encode the bytes to a base64 string:
String base64String = base64Encode(bytes);
// ...
}
// ...
},
)
Note: In the above example, we are rotating the image by -90 degrees before converting it to png. This is because images from the camera are often rotated depending on the device orientation. You can adjust this value based on the rotation needed to get the image in the correct orientation.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-01-02 11:00:00 +0000
Seen: 11 times
Last updated: Mar 29 '22