How to convert RGB pixmap to ui.Image in Dart?

Issue

Currently I have a Uint8List, formatted like [R,G,B,R,G,B,…] for all the pixels of the image. And of course I have its width and height.

I found decodeImageFromPixels while searching but it only takes RGBA/BGRA format. I converted my pixmap from RGB to RGBA and this function works fine.

However, my code now looks like this:

Uint8List rawPixel = raw.value.asTypedList(w * h * channel);
List<int> rgba = [];
for (int i = 0; i < rawPixel.length; i++) {
  rgba.add(rawPixel[i]);
    if ((i + 1) % 3 == 0) {
      rgba.add(0);
    }
}

Uint8List rgbaList = Uint8List.fromList(rgba);

Completer<Image> c = Completer<Image>();
decodeImageFromPixels(rgbaList, w, h, PixelFormat.rgba8888, (Image img) {
  c.complete(img);
});

I have to make a new list(waste in space) and iterate through the entire list(waste in time).

This is too inefficient in my opinion, is there any way to make this more elegant? Like add a new PixelFormat.rgb888?

Thanks in advance.

Solution

You may find that this loop is faster as it doesn’t keep appending to the list and then copy it at the end.

  final rawPixel = raw.value.asTypedList(w * h * channel);
  final rgbaList = Uint8List(w * h + 4); // create the Uint8List directly as we know the width and height

  for (var i = 0; i < w * h; i++) {
    final rgbOffset = i * 3;
    final rgbaOffset = i * 4;
    rgbaList[rgbaOffset] = rawPixel[rgbOffset]; // red
    rgbaList[rgbaOffset + 1] = rawPixel[rgbOffset + 1]; // green
    rgbaList[rgbaOffset + 2] = rawPixel[rgbOffset + 2]; // blue
    rgbaList[rgbaOffset + 3] = 255; // a
  }

An alternative is to prepend the array with a BMP header by adapting this answer (though it would simpler as there would be no palette) and passing that bitmap to instantiateImageCodec as that code is presumably highly optimized for parsing bitmaps.

Answered By – Richard Heap

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *