instantiateImageCodec function Null safety

Future<Codec> instantiateImageCodec(
  1. Uint8List list,
  2. {int? targetWidth,
  3. int? targetHeight,
  4. bool allowUpscaling = true}
)

Instantiates an image Codec.

This method is a convenience wrapper around the ImageDescriptor API, and using ImageDescriptor directly is preferred since it allows the caller to make better determinations about how and whether to use the targetWidth and targetHeight parameters.

The list parameter is the binary image data (e.g a PNG or GIF binary data). The data can be for either static or animated images. The following image formats are supported: JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP. Additional formats may be supported by the underlying platform. Flutter will attempt to call platform API to decode unrecognized formats, and if the platform API supports decoding the image Flutter will be able to render it.

The targetWidth and targetHeight arguments specify the size of the output image, in image pixels. If they are not equal to the intrinsic dimensions of the image, then the image will be scaled after being decoded. If the allowUpscaling parameter is not set to true, both dimensions will be capped at the intrinsic dimensions of the image, even if only one of them would have exceeded those intrinsic dimensions. If exactly one of these two arguments is specified, then the aspect ratio will be maintained while forcing the image to match the other given dimension. If neither is specified, then the image maintains its intrinsic size.

Scaling the image to larger than its intrinsic size should usually be avoided, since it causes the image to use more memory than necessary. Instead, prefer scaling the Canvas transform. If the image must be scaled up, the allowUpscaling parameter must be set to true.

The returned future can complete with an error if the image decoding has failed.

Implementation

Future<Codec> instantiateImageCodec(
  Uint8List list, {
  int? targetWidth,
  int? targetHeight,
  bool allowUpscaling = true,
}) async {
  final ImmutableBuffer buffer = await ImmutableBuffer.fromUint8List(list);
  final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer);
  if (!allowUpscaling) {
    if (targetWidth != null && targetWidth > descriptor.width) {
      targetWidth = descriptor.width;
    }
    if (targetHeight != null && targetHeight > descriptor.height) {
      targetHeight = descriptor.height;
    }
  }
  buffer.dispose();
  return descriptor.instantiateCodec(
    targetWidth: targetWidth,
    targetHeight: targetHeight,
  );
}