Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 393
itzMeerkat Avatar asked Oct 20 '25 02:10

itzMeerkat


1 Answers

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.

like image 117
Richard Heap Avatar answered Oct 22 '25 08:10

Richard Heap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!