Converting matrix of colors to image in flutter

Viewed 78

I need to convert List<List<int>>> to an dart:ui.Image. I have an algorithm to convert an integer to a color. I tried to do this by drawing one-pixel rectangles on the dart:ui.Canvas, but it is about 100 times slower than I expected! _getPixelColor is the method by which I convert int to Color. Here is my code:

Future<void> matrixToImage(FField sourceMatrix) async {

  PictureRecorder p = PictureRecorder();
  Canvas c = Canvas(
      p,
      Rect.fromLTWH(0, 0, sourceMatrix.length.toDouble(),
          sourceMatrix[0].length.toDouble()));

  Paint paint = Paint();

  for (int x = 0; x < sourceMatrix.length; x++) {
    for (int y = 0; y < sourceMatrix[0].length; y++) {
      int pixelValue = sourceMatrix[x][y];      
        
      paint.color = _getPixelColor(pixelValue / 40 / paletteLength + paletteOffset); 

      c.drawRect(Rect.fromLTWH(x.toDouble(), y.toDouble(), 1, 1), paint);

    }
  }

  Picture picture = p.endRecording();

  Image result = await picture.toImage(sourceMatrix.length, sourceMatrix[0].length);

}
2 Answers

If you can compute your int value to an int value that the Image class understands, you don't need the detour through canvas drawing.

Just use Image.fromBytes with the .value of the Color as the list of ints.

That depends on how the image data is stored in the list of INTs.

Generally, I like this package to manipulate images and display them:

https://pub.dev/packages/image

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

im.Image? img = decodeImage(bytes); // different-IMAGE class !

Uint8List uint8list = getEncodedJpg(img!,quality: 85) as Uint8List;


// ...

build(BuildContext context) {
  return Container(child:
    Image.memory(uint8list) // material-IMAGE class !
  );
}
Related