Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To convert a CameraImage stream into bytes or a file in Flutter, you can use the following steps:

  1. Import the necessary libraries:
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;
  1. Define a function that takes in the CameraImage and converts it to a Uint8List:
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;
}
  1. Call the function inside your CameraController image stream:
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.