Skip to content

Commit 604efe3

Browse files
YeungKCsuryaKommana2662
authored andcommitted
Do not derive a decode size of 0 for very thin images (flutter#194669)
Fixes flutter#194668 A very thin image does not decode when the decode size is derived from one side. Example: a 4000x1 PNG with `cacheWidth: 100`. The derived height is `100 ~/ 4000 = 0`, and the decode fails. Observed on stable 3.47.7 (the same code is on master): | Call (4000x1 or 1x4000 PNG) | Result | | --- | --- | | `Image.memory(..., cacheWidth: 100)` / `ResizeImage(width: 100)` | `Exception: Codec failed to produce an image` (log: `Could not resize to empty dimensions.`) | | `ResizeImage(height: 100)` on 1x4000 | same exception | | `ResizeImage(width: 100, policy: ResizeImagePolicy.fit)` (with or without `allowUpscaling`, with or without `height`) | debug: the assertion `height == null \|\| height > 0` (or `width == null \|\| width > 0`) in `TargetImageSize` fails. By reading the code, in release mode the 0 becomes null, `instantiateCodec` derives 0 again, and the codec fails. | | `ImageDescriptor.instantiateCodec(targetWidth: 100)` / `ui.instantiateImageCodec(targetWidth: 100)` | same exception | This change clamps each derived side to at least 1 pixel: * `ImageDescriptor.instantiateCodec` in `dart:ui` (`lib/ui/painting.dart`). This is the path for `cacheWidth` or `cacheHeight` with one side, and for `instantiateImageCodec` with one target side. * `scaledImageSize` in the web engine, which has the same derivation. * `ResizeImage` with `ResizeImagePolicy.fit`. The clamp is on each side that a branch derives from the aspect ratio. A side that the caller gives is not changed, so an explicit 0 still fails at decode time, as before, and is not changed to 1. `useLogicalSize` uses `ceil`, so it cannot give 0. ## Tests * `packages/flutter/test/painting/image_provider_resize_image_test.dart`: 4000x1 and 1x4000 images with `policy: fit` decode to 100x1 and 1x100. This test fails without the change (assertion in `TargetImageSize`) and passes with it. The painting, image and fade tests pass locally. * `packages/flutter/test/painting/image_provider_resize_image_test.dart`: `ResizeImage` with `width` or `height` of 0 still fails to decode with `policy: exact` and `policy: fit`. * `engine/src/flutter/testing/dart/codec_test.dart`: `instantiateImageCodec(targetWidth: 100)` on 4000x1 gives 100x1, and `targetHeight: 100` on 1x4000 gives 1x100. * `engine/src/flutter/lib/web_ui/test/ui/image_test.dart`: `scaledImageSize` returns 100x1 and 1x100 for the same inputs. I did not build the engine locally, so the `codec_test.dart` and web tests run only in CI. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [ ] I updated/added relevant documentation (doc comments with `///`). No doc change is necessary. - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [ ] All existing and new tests are passing. The framework tests pass locally. The engine and web tests run only in CI. [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/
1 parent a7e2820 commit 604efe3

6 files changed

Lines changed: 107 additions & 10 deletions

File tree

‎engine/src/flutter/lib/ui/painting.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9121,9 +9121,9 @@ base class _NativeImageDescriptor extends NativeFieldWrapperClass1 implements Im
91219121
targetWidth = width;
91229122
targetHeight = height;
91239123
} else if (targetWidth == null && targetHeight != null) {
9124-
targetWidth = (targetHeight * (width / height)).round();
9124+
targetWidth = math.max(1, (targetHeight * (width / height)).round());
91259125
} else if (targetHeight == null && targetWidth != null) {
9126-
targetHeight = targetWidth ~/ (width / height);
9126+
targetHeight = math.max(1, targetWidth ~/ (width / height));
91279127
}
91289128
assert(targetWidth != null);
91299129
assert(targetHeight != null);

‎engine/src/flutter/lib/web_ui/lib/src/engine/image_decoder.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -522,12 +522,12 @@ BitmapSize? scaledImageSize(int width, int height, int? targetWidth, int? target
522522
if (targetHeight == null || targetHeight == height) {
523523
return null;
524524
}
525-
targetWidth = (width * targetHeight / height).round();
525+
targetWidth = math.max(1, (width * targetHeight / height).round());
526526
} else if (targetHeight == null) {
527527
if (targetWidth == width) {
528528
return null;
529529
}
530-
targetHeight = (height * targetWidth / width).round();
530+
targetHeight = math.max(1, (height * targetWidth / width).round());
531531
}
532532
return BitmapSize(targetWidth, targetHeight);
533533
}

‎engine/src/flutter/lib/web_ui/test/ui/image_test.dart‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@ Future<void> testMain() async {
6767
expect(size?.height, 300);
6868
});
6969

70+
test('scaledImageSize does not derive a side of 0 for a very thin image', () {
71+
final BitmapSize? wide = scaledImageSize(4000, 1, 100, null);
72+
expect(wide?.width, 100);
73+
expect(wide?.height, 1);
74+
final BitmapSize? tall = scaledImageSize(1, 4000, null, 100);
75+
expect(tall?.width, 1);
76+
expect(tall?.height, 100);
77+
});
78+
7079
test('instantiateImageCodecFromBuffer dispose buffer', () async {
7180
final ui.Image image = await _createImage();
7281
final ByteData? imageData = await image.toByteData(format: ui.ImageByteFormat.png);

‎engine/src/flutter/testing/dart/codec_test.dart‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,32 @@ void main() {
129129
);
130130
});
131131

132+
test('does not derive a side of 0 for a very thin image', () async {
133+
Future<List<int>> decode(int width, int height, {int? targetWidth, int? targetHeight}) async {
134+
final recorder = ui.PictureRecorder();
135+
ui.Canvas(recorder).drawRect(
136+
ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
137+
ui.Paint()..color = const ui.Color(0xFF0000FF),
138+
);
139+
final ui.Image image = await recorder.endRecording().toImage(width, height);
140+
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
141+
image.dispose();
142+
final ui.Codec codec = await ui.instantiateImageCodec(
143+
data!.buffer.asUint8List(),
144+
targetWidth: targetWidth,
145+
targetHeight: targetHeight,
146+
);
147+
final ui.FrameInfo frameInfo = await codec.getNextFrame();
148+
final size = <int>[frameInfo.image.width, frameInfo.image.height];
149+
frameInfo.image.dispose();
150+
codec.dispose();
151+
return size;
152+
}
153+
154+
expect(await decode(4000, 1, targetWidth: 100), <int>[100, 1]);
155+
expect(await decode(1, 4000, targetHeight: 100), <int>[1, 100]);
156+
});
157+
132158
test('disposed decoded image', () async {
133159
final Uint8List data = await _getSkiaResource('flutter_logo.jpg').readAsBytes();
134160
final ui.Codec codec = await ui.instantiateImageCodec(data);

‎packages/flutter/lib/src/painting/image_provider.dart‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,8 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
14121412

14131413
return ui.TargetImageSize(width: targetWidth, height: targetHeight);
14141414
case ResizeImagePolicy.fit:
1415+
// A very thin image can derive a side of 0, which cannot be decoded.
1416+
// Clamp only the derived sides, so that a given side of 0 still fails.
14151417
final double aspectRatio = intrinsicWidth / intrinsicHeight;
14161418
final int maxWidth = effectiveWidth ?? intrinsicWidth;
14171419
final int maxHeight = effectiveHeight ?? intrinsicHeight;
@@ -1420,25 +1422,25 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
14201422

14211423
if (targetWidth > maxWidth) {
14221424
targetWidth = maxWidth;
1423-
targetHeight = targetWidth ~/ aspectRatio;
1425+
targetHeight = math.max(1, targetWidth ~/ aspectRatio);
14241426
}
14251427

14261428
if (targetHeight > maxHeight) {
14271429
targetHeight = maxHeight;
1428-
targetWidth = (targetHeight * aspectRatio).floor();
1430+
targetWidth = math.max(1, (targetHeight * aspectRatio).floor());
14291431
}
14301432

14311433
if (allowUpscaling) {
14321434
if (effectiveWidth == null) {
14331435
assert(effectiveHeight != null);
14341436
targetHeight = effectiveHeight!;
1435-
targetWidth = (targetHeight * aspectRatio).floor();
1437+
targetWidth = math.max(1, (targetHeight * aspectRatio).floor());
14361438
} else if (effectiveHeight == null) {
14371439
targetWidth = effectiveWidth;
1438-
targetHeight = targetWidth ~/ aspectRatio;
1440+
targetHeight = math.max(1, targetWidth ~/ aspectRatio);
14391441
} else {
1440-
final int derivedMaxWidth = (maxHeight * aspectRatio).floor();
1441-
final int derivedMaxHeight = maxWidth ~/ aspectRatio;
1442+
final int derivedMaxWidth = math.max(1, (maxHeight * aspectRatio).floor());
1443+
final int derivedMaxHeight = math.max(1, maxWidth ~/ aspectRatio);
14421444
targetWidth = math.min(maxWidth, derivedMaxWidth);
14431445
targetHeight = math.min(maxHeight, derivedMaxHeight);
14441446
}

‎packages/flutter/test/painting/image_provider_resize_image_test.dart‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ void main() {
2121
});
2222

2323
group('ResizeImage', () {
24+
test('fails to decode when a given width or height is 0', () async {
25+
final image = MemoryImage(Uint8List.fromList(kBlueSquarePng));
26+
for (final policy in <ResizeImagePolicy>[ResizeImagePolicy.exact, ResizeImagePolicy.fit]) {
27+
// The constructor accepts 0. The failure occurs at decode time.
28+
for (final resizedImage in <ResizeImage>[
29+
ResizeImage(image, width: 0, policy: policy),
30+
ResizeImage(image, height: 0, policy: policy),
31+
]) {
32+
expect(await _resolveAndGetError(resizedImage), isAssertionError);
33+
PaintingBinding.instance.imageCache.clear();
34+
}
35+
}
36+
});
37+
2438
group('equality and hashCode', () {
2539
test('Two identical instances should be equal and have same hashCode', () {
2640
final bytes = Uint8List.fromList(kTransparentImage);
@@ -379,9 +393,30 @@ void main() {
379393
);
380394
await _expectImageSize(resizedImage, const Size(50, 50));
381395
});
396+
397+
test('does not derive a side of 0 for a very thin image', () async {
398+
final rawImage = MemoryImage(await _createPng(4000, 1));
399+
await _expectImageSize(
400+
ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit),
401+
const Size(100, 1),
402+
);
403+
final tallImage = MemoryImage(await _createPng(1, 4000));
404+
await _expectImageSize(
405+
ResizeImage(tallImage, height: 100, policy: ResizeImagePolicy.fit),
406+
const Size(1, 100),
407+
);
408+
});
382409
});
383410

384411
group('with policy=fit and allowResize=true', () {
412+
test('does not derive a side of 0 for a very thin image', () async {
413+
final rawImage = MemoryImage(await _createPng(4000, 1));
414+
await _expectImageSize(
415+
ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true),
416+
const Size(100, 1),
417+
);
418+
});
419+
385420
test('constrains square image to bounded portrait rect', () async {
386421
final rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng));
387422
await _expectImageSize(rawImage, const Size(50, 50));
@@ -691,6 +726,18 @@ void main() {
691726
});
692727
}
693728

729+
Future<Uint8List> _createPng(int width, int height) async {
730+
final recorder = ui.PictureRecorder();
731+
ui.Canvas(recorder).drawRect(
732+
ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
733+
ui.Paint()..color = const ui.Color(0xFF0000FF),
734+
);
735+
final ui.Image image = await recorder.endRecording().toImage(width, height);
736+
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
737+
image.dispose();
738+
return data!.buffer.asUint8List();
739+
}
740+
694741
Future<void> _expectImageSize(ImageProvider<Object> imageProvider, Size size) async {
695742
final Size actualSize = await _resolveAndGetSize(imageProvider);
696743
expect(actualSize, size);
@@ -711,6 +758,19 @@ Future<Size> _resolveAndGetSize(
711758
return completer.future;
712759
}
713760

761+
Future<Object> _resolveAndGetError(ImageProvider imageProvider) {
762+
final completer = Completer<Object>();
763+
imageProvider
764+
.resolve(ImageConfiguration.empty)
765+
.addListener(
766+
ImageStreamListener(
767+
(ImageInfo image, bool synchronousCall) => completer.complete(image),
768+
onError: (Object error, StackTrace? stackTrace) => completer.complete(error),
769+
),
770+
);
771+
return completer.future;
772+
}
773+
714774
// This version of MemoryImage guarantees obtainKey returns a future that has not been
715775
// completed synchronously.
716776
class _AsyncKeyMemoryImage extends MemoryImage {

0 commit comments

Comments
 (0)