imageFromBytes function Assets and loading
Decodes an encoded image (PNG, JPEG, etc.) from raw bytes.
Uses dart:ui's built-in image codecs. When maxWidth is set and the
image is wider, it is decoded scaled down to maxWidth (aspect ratio
preserved); a narrower image is never upscaled. Throws if the bytes can't
be decoded as an image.
Implementation
Future<ui.Image> imageFromBytes(Uint8List bytes, {int? maxWidth}) async {
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
final ui.Codec codec;
ui.ImageDescriptor? descriptor;
if (maxWidth == null) {
codec = await ui.instantiateImageCodecFromBuffer(buffer);
} else {
descriptor = await ui.ImageDescriptor.encoded(buffer);
codec = await descriptor.instantiateCodec(
targetWidth: descriptor.width <= maxWidth ? null : maxWidth,
);
}
final frame = await codec.getNextFrame();
descriptor?.dispose();
return frame.image;
}