instantiateImageCodecWithSize function
- ImmutableBuffer buffer, {
- TargetImageSizeCallback? getTargetSize,
Instantiates an image Codec.
This method is a convenience wrapper around the ImageDescriptor API.
The buffer
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 buffer
will be disposed by this method once the codec has been
created, so the caller must relinquish ownership of the buffer
when they
call this method.
The getTargetSize
parameter, when specified, will be invoked and passed
the image's intrinsic size to determine the size to decode the image to.
The width and the height of the size it returns must be positive values
greater than or equal to 1, or null. It is valid to return a
TargetImageSize that specifies only one of width
and height
with the
other remaining null, in which case the omitted dimension will be scaled to
maintain the aspect ratio of the original dimensions. When both are null or
omitted, the image will be decoded at its native resolution (as will be the
case if the getTargetSize
parameter is omitted).
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.
The returned future can complete with an error if the image decoding has failed.
Compatibility note on the web
When running Flutter on the web, only the CanvasKit renderer supports image resizing capabilities (not the HTML renderer). So if image resizing is critical to your use case, and you're deploying to the web, you should build using the CanvasKit renderer.
Implementation
Future<Codec> instantiateImageCodecWithSize(
ImmutableBuffer buffer, {
TargetImageSizeCallback? getTargetSize,
}) async {
getTargetSize ??= _getDefaultImageSize;
final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer);
try {
final TargetImageSize targetSize = getTargetSize(descriptor.width, descriptor.height);
assert(targetSize.width == null || targetSize.width! > 0);
assert(targetSize.height == null || targetSize.height! > 0);
return descriptor.instantiateCodec(
targetWidth: targetSize.width,
targetHeight: targetSize.height,
);
} finally {
buffer.dispose();
}
}