imageFromBytes function Assets and loading

Future<Image> imageFromBytes(
  1. Uint8List bytes, {
  2. int? maxWidth,
})

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);
  // Not ImageDescriptor, which the web engine does not implement.
  final codec = await ui.instantiateImageCodecWithSize(
    buffer,
    getTargetSize: (width, height) => maxWidth == null || width <= maxWidth
        ? const ui.TargetImageSize()
        : ui.TargetImageSize(width: maxWidth),
  );
  final frame = await codec.getNextFrame();
  return frame.image;
}