Convert Image object to rgb pixel array and back in Flutter

Viewed 6976

Is there a way to get an image's rgb matrix representation? and vice versa? I would like to perform image masking/filtering on the original image so it needs to be applied to its rgb matrix representation. Currently using this library to get an image from a device: https://pub.dartlang.org/packages/image_picker

3 Answers
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

// for a local iamge example
List RGBAList;
// 1. get [ImageProvider] instance
//    [ExactAssetImage] extends [AssetBundleImageProvider] extends [ImageProvider]
ExactAssetImage provider = ExactAssetImage('$local_img_uri');

// 2. get [ui.Image] by [ImageProvider]
ImageStream stream = provider.resolve(ImageConfiguration.empty);
Completer completer = Completer<ui.Image>();
ImageStreamListener listener = ImageStreamListener((frame, sync) {
    ui.Image image = frame.image;
    completer.complete(image);
    stream.removeListener(listener);
})
stream.addListener(listener);

// 3. get rgba array/list by [ui.Image]
completer.then((ui.Image image) {
    image.toByteData(format: ui.ImageByteFormat.rowRgba).then((ByteData data) {
        RGBAList = data.buffer.asUint8List().toList();
    }); 
})

You can use this package - https://pub.dartlang.org/packages/image

import 'package:image/image.dart' as Imagi;

Here's how to use it to obtain RGB matrix of a file from ImagePicker()-

final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
      final imageTemp = File(image.path);
controlImage = imageTemp;

Now here's a function for obtaining the RGB matrix -

  List<List<int>> imgArray = [];
 void readImage() async{

    final bytes = await controlImage!.readAsBytes();
    final decoder = Imagi.JpegDecoder();
    final decodedImg = decoder.decodeImage(bytes);
    final decodedBytes = decodedImg!.getBytes(format: Imagi.Format.rgb);
    // print(decodedBytes);
    print(decodedBytes.length);

    // int loopLimit = decodedImg.width;
    int loopLimit =1000;
    for(int x = 0; x < loopLimit; x++) {
      int red = decodedBytes[decodedImg.width*3 + x*3];
      int green = decodedBytes[decodedImg.width*3 + x*3 + 1];
      int blue = decodedBytes[decodedImg.width*3 + x*3 + 2];
      imgArray.add([red, green, blue]);
    }
    print(imgArray);

  }

The array imgArray will contain the RGB matrix

Related