import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; /// An image's bytes decoded no larger than needed to cover a box of /// [width] x [height] device pixels (as `BoxFit.cover` shows it), keeping the /// image's aspect ratio and never upscaling. A gallery of full-size pictures /// then holds thumbnails, not originals, in memory. @immutable class CoverSizedMemoryImage extends ImageProvider { const CoverSizedMemoryImage( this.bytes, { required this.width, required this.height, }); final Uint8List bytes; final int width; final int height; @override Future obtainKey(ImageConfiguration configuration) => SynchronousFuture(this); @override ImageStreamCompleter loadImage( CoverSizedMemoryImage key, ImageDecoderCallback decode, ) => MultiFrameImageStreamCompleter( codec: _decode(key, decode), scale: 1, debugLabel: 'CoverSizedMemoryImage(${describeIdentity(key.bytes)})', ); static Future _decode( CoverSizedMemoryImage key, ImageDecoderCallback decode, ) async { final buffer = await ui.ImmutableBuffer.fromUint8List(key.bytes); return decode( buffer, getTargetSize: (intrinsicWidth, intrinsicHeight) => coverTargetSize( intrinsicWidth, intrinsicHeight, width: key.width, height: key.height, ), ); } @override bool operator ==(Object other) => other is CoverSizedMemoryImage && identical(other.bytes, bytes) && other.width == width && other.height == height; @override int get hashCode => Object.hash(identityHashCode(bytes), width, height); } /// The decode size that still covers a [width] x [height] box: the picture's /// aspect ratio scaled down until its shorter side fits, never scaled up. ui.TargetImageSize coverTargetSize( int intrinsicWidth, int intrinsicHeight, { required int width, required int height, }) { final scale = math.max(width / intrinsicWidth, height / intrinsicHeight); if (scale >= 1) return const ui.TargetImageSize(); return ui.TargetImageSize( width: math.max(1, (intrinsicWidth * scale).ceil()), height: math.max(1, (intrinsicHeight * scale).ceil()), ); }