Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a UInt8List to Image in flutter/dart-ui

Tags:

flutter

dart

I have this scenario where I have to get a UInt8List from an image like that:

List stuff = image.toByteData().buffer.asUInt8List()

Do some manipulations and get back to a Image.

I've tried the following:

List stuff = image.toByteData().buffer.asUInt8List()
ui.decodeImageFromList(stuff, (image){
  // do stuff with image
});

But I keep getting this Exception:

E/flutter (10201): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
E/flutter (10201): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
...

Take notice that even without any changes in the List the exception is thrown. How can I make the list have a encodable format?

like image 368
Renan C. Araujo Avatar asked Jan 03 '19 21:01

Renan C. Araujo


3 Answers

You can use memory image as given below, for the direct byte rendering

child: Image.memory(Uint8List bytes);
like image 54
Kishan Donga Avatar answered Oct 20 '22 00:10

Kishan Donga


You can use MemoryImage class to convert a Uint8List to image.

var _image = MemoryImage(image);

You can find more details about this class here

like image 6
Firosh Vasudevan Avatar answered Oct 20 '22 02:10

Firosh Vasudevan


ui.Image can turn itself into an RGBA bitmap (or PNG), but cannot convert itself back from a bitmap. (The reason for this is that there isn't any way to tell the image codec things like the color depth, geometry, etc.) The solution is to add a BMP file header onto the front of your bitmap, where you can describe those missing things, then pass that to instantiateImageCodec. See this answer, but note that in that case the bitmap in question had a strange packed color map. In your case of 32 bit RGBA, the header would be even simpler.

like image 4
Richard Heap Avatar answered Oct 20 '22 00:10

Richard Heap