diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index 84e44f4759..02e97ee3d7 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -1024,6 +1024,14 @@ enum Clip { // constant and can't propagate into the set/get calls. const Endian _kFakeHostEndian = Endian.little; +// Indicates that the image should not be resized in this dimension. +// +// Used by [instantiateImageCodec] as a magical value to disable resizing +// in the given dimension. +// +// This needs to be kept in sync with "kDoNotResizeDimension" in codec.cc +const int _kDoNotResizeDimension = -1; + /// A description of the style to use when drawing on a [Canvas]. /// /// Most APIs on [Canvas] take a [Paint] object to describe the style @@ -1651,20 +1659,37 @@ class Codec extends NativeFieldWrapperClass2 { /// unlikely that a factor that low will be sufficient to cache all decoded /// frames. The default value is `25.0`. /// +/// 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 exactly one of +/// these two arguments is specified, then the aspect ratio will be maintained +/// while forcing the image to match the specified dimension. If both are not +/// specified, then the image maintains its real size. +/// /// The returned future can complete with an error if the image decoding has /// failed. Future instantiateImageCodec(Uint8List list, { double decodedCacheRatioCap = 0, + int targetWidth, + int targetHeight, }) { return _futurize( - (_Callback callback) => _instantiateImageCodec(list, callback, null, decodedCacheRatioCap), + (_Callback callback) => _instantiateImageCodec(list, callback, null, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) ); } /// Instantiates a [Codec] object for an image binary data. /// +/// The [targetWidth] and [targetHeight] arguments specify the size of the output +/// image, in image pixels. Image in this context refers to image in every frame of the [Codec]. +/// If [targetWidth] and [targetHeight] are not equal to the intrinsic dimensions of the +/// image, then the image will be scaled after being decoded. If exactly one of +/// these two arguments is not equal to [_kDoNotResizeDimension], then the aspect +/// ratio will be maintained while forcing the image to match the given dimension. +/// If both are equal to [_kDoNotResizeDimension], then the image maintains its real size. +/// /// Returns an error message if the instantiation has failed, null otherwise. -String _instantiateImageCodec(Uint8List list, _Callback callback, _ImageInfo imageInfo, double decodedCacheRatioCap) +String _instantiateImageCodec(Uint8List list, _Callback callback, _ImageInfo imageInfo, double decodedCacheRatioCap, int targetWidth, int targetHeight) native 'instantiateImageCodec'; /// Loads a single image frame from a byte array into an [Image] object. @@ -1698,17 +1723,24 @@ Future _decodeImageFromListAsync(Uint8List list, /// multiple) animated images. Note that GIFs are highly compressed, and it's /// unlikely that a factor that low will be sufficient to cache all decoded /// frames. The default value is `25.0`. +/// +/// 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 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 real size. void decodeImageFromPixels( Uint8List pixels, int width, int height, PixelFormat format, ImageDecoderCallback callback, - {int rowBytes, double decodedCacheRatioCap = 0} + {int rowBytes, double decodedCacheRatioCap = 0, int targetWidth, int targetHeight} ) { final _ImageInfo imageInfo = _ImageInfo(width, height, format.index, rowBytes); final Future codecFuture = _futurize( - (_Callback callback) => _instantiateImageCodec(pixels, callback, imageInfo, decodedCacheRatioCap) + (_Callback callback) => _instantiateImageCodec(pixels, callback, imageInfo, decodedCacheRatioCap, targetWidth ?? _kDoNotResizeDimension, targetHeight ?? _kDoNotResizeDimension) ); codecFuture.then((Codec codec) => codec.getNextFrame()) .then((FrameInfo frameInfo) => callback(frameInfo.image)); diff --git a/engine/src/flutter/lib/ui/painting/codec.cc b/engine/src/flutter/lib/ui/painting/codec.cc index ec724957c5..ee072a2d73 100644 --- a/engine/src/flutter/lib/ui/painting/codec.cc +++ b/engine/src/flutter/lib/ui/painting/codec.cc @@ -28,6 +28,9 @@ namespace { static constexpr const char* kInitCodecTraceTag = "InitCodec"; static constexpr const char* kCodecNextFrameTraceTag = "CodecNextFrame"; +// This needs to be kept in sync with _kDoNotResizeDimension in painting.dart +const int kDoNotResizeDimension = -1; + // This must be kept in sync with the enum in painting.dart enum PixelFormat { kRGBA8888, @@ -79,10 +82,118 @@ static sk_sp DecodeImage(fml::WeakPtr context, } } +// Returns true if the image needs to be resized. +// +// newWidth and newHeight will reflect the dimensions that the image should +// be scaled to. +// +// 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 exactly one +// of these two arguments is equal to kDoNotResizeDimension, then the aspect +// ratio will be maintained while forcing the image to match the other given +// dimension. If both are equal to kDoNotResizeDimension, then the image +// maintains its real size. +static bool needsResize(const int currentWidth, + const int currentHeight, + const int targetWidth, + const int targetHeight, + int& newWidth, + int& newHeight) { + newWidth = currentWidth; + newHeight = currentHeight; + if (targetWidth == kDoNotResizeDimension && + targetHeight == kDoNotResizeDimension) { + return false; + } + + if (currentWidth == targetWidth && currentHeight == targetHeight) { + return false; + } + + if (targetWidth == kDoNotResizeDimension) { + newHeight = targetHeight; + const double aspectRatio = (double)currentWidth / currentHeight; + newWidth = round(aspectRatio * newHeight); + return true; + } else if (targetHeight == kDoNotResizeDimension) { + newWidth = targetWidth; + const double invAspectRatio = (double)currentHeight / currentWidth; + newHeight = round(invAspectRatio * newWidth); + return true; + } else { + newWidth = targetWidth; + newHeight = targetHeight; + return true; + } +} + +static sk_sp ResizeImageToExactSize(fml::WeakPtr context, + sk_sp image, + SkImageInfo scaledImageInfo) { + if (image == nullptr || !image.get()) { + FML_LOG(ERROR) << "Failed to decode image."; + return nullptr; + } + + SkBitmap bitmap = SkBitmap(); + if (!bitmap.tryAllocPixels(scaledImageInfo)) { + FML_LOG(ERROR) << "Failed to allocate bitmap."; + return nullptr; + } + + if (!image->scalePixels(bitmap.pixmap(), kLow_SkFilterQuality)) { + FML_LOG(ERROR) << "Failed to scale pixels."; + return nullptr; + } + + // This indicates that we do not want a "linear blending" decode. + sk_sp dstColorSpace = nullptr; + GrContext* grContext = context ? context.get() : nullptr; + return SkImage::MakeCrossContextFromPixmap(grContext, bitmap.pixmap(), true, + dstColorSpace.get(), true); +} + +static sk_sp DecodeAndResizeImageToExactSize( + fml::WeakPtr context, + SkImageInfo scaledImageInfo, + sk_sp buffer, + size_t trace_id) { + TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); + TRACE_EVENT0("flutter", "DecodeAndResizeImageToExactSize"); + + // Do not create a cross context image here, since it can not be resized. + sk_sp image = SkImage::MakeFromEncoded(std::move(buffer)); + return ResizeImageToExactSize(context, image, scaledImageInfo); +} + +static sk_sp DecodeAndResizeImage(fml::WeakPtr context, + std::unique_ptr& skCodec, + sk_sp buffer, + const int targetWidth, + const int targetHeight, + size_t trace_id) { + const SkImageInfo imageInfo = skCodec->getInfo(); + + const int width = imageInfo.width(); + const int height = imageInfo.height(); + + int newWidth, newHeight; + if (needsResize(width, height, targetWidth, targetHeight, newWidth, + newHeight)) { + return DecodeAndResizeImageToExactSize( + context, imageInfo.makeWH(newWidth, newHeight), buffer, trace_id); + } else { + return DecodeImage(context, buffer, trace_id); + } +} + fml::RefPtr InitCodec(fml::WeakPtr context, sk_sp buffer, fml::RefPtr unref_queue, const float decodedCacheRatioCap, + const int targetWidth, + const int targetHeight, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("blink", "InitCodec"); @@ -102,9 +213,12 @@ fml::RefPtr InitCodec(fml::WeakPtr context, return fml::MakeRefCounted(std::move(skCodec), decodedCacheRatioCap); } - auto skImage = DecodeImage(context, buffer, trace_id); + + auto skImage = DecodeAndResizeImage(context, skCodec, buffer, targetWidth, + targetHeight, trace_id); + FML_DCHECK(skImage) << "Unable to resize the image to (w, h): " << targetWidth + << ", " << targetHeight << "."; if (!skImage) { - FML_LOG(ERROR) << "DecodeImage failed"; return nullptr; } auto image = CanvasImage::Create(); @@ -119,6 +233,8 @@ fml::RefPtr InitCodecUncompressed( ImageInfo image_info, fml::RefPtr unref_queue, const float decodedCacheRatioCap, + int targetWidth, + int targetHeight, size_t trace_id) { TRACE_FLOW_STEP("flutter", kInitCodecTraceTag, trace_id); TRACE_EVENT0("blink", "InitCodecUncompressed"); @@ -129,7 +245,14 @@ fml::RefPtr InitCodecUncompressed( } sk_sp skImage; - if (context) { + int newWidth, newHeight; + if (needsResize(image_info.sk_info.width(), image_info.sk_info.height(), + targetWidth, targetHeight, newWidth, newHeight)) { + auto imageToResize = SkImage::MakeRasterData( + image_info.sk_info, std::move(buffer), image_info.row_bytes); + skImage = ResizeImageToExactSize( + context, imageToResize, image_info.sk_info.makeWH(newWidth, newHeight)); + } else if (context) { SkPixmap pixmap(image_info.sk_info, buffer->data(), image_info.row_bytes); skImage = SkImage::MakeCrossContextFromPixmap(context.get(), pixmap, true, nullptr, true); @@ -152,15 +275,18 @@ void InitCodecAndInvokeCodecCallback( sk_sp buffer, std::unique_ptr image_info, const float decodedCacheRatioCap, + const int targetWidth, + const int targetHeight, size_t trace_id) { fml::RefPtr codec; if (image_info) { codec = InitCodecUncompressed(context, std::move(buffer), *image_info, std::move(unref_queue), decodedCacheRatioCap, - trace_id); + targetWidth, targetHeight, trace_id); } else { - codec = InitCodec(context, std::move(buffer), std::move(unref_queue), - decodedCacheRatioCap, trace_id); + codec = + InitCodec(context, std::move(buffer), std::move(unref_queue), + decodedCacheRatioCap, targetWidth, targetHeight, trace_id); } ui_task_runner->PostTask( fml::MakeCopyable([callback = std::move(callback), @@ -281,6 +407,11 @@ void InstantiateImageCodec(Dart_NativeArguments args) { const float decodedCacheRatioCap = tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 3)); + const int targetWidth = + tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 4)); + const int targetHeight = + tonic::DartConverter::FromDart(Dart_GetNativeArgument(args, 5)); + auto buffer = SkData::MakeWithCopy(list.data(), list.num_elements()); auto* dart_state = UIDartState::Current(); @@ -293,11 +424,11 @@ void InstantiateImageCodec(Dart_NativeArguments args) { ui_task_runner = task_runners.GetUITaskRunner(), context = dart_state->GetResourceContext(), queue = UIDartState::Current()->GetSkiaUnrefQueue(), - decodedCacheRatioCap]() mutable { + decodedCacheRatioCap, targetWidth, targetHeight]() mutable { InitCodecAndInvokeCodecCallback( std::move(ui_task_runner), context, std::move(queue), std::move(callback), std::move(buffer), std::move(image_info), - decodedCacheRatioCap, trace_id); + decodedCacheRatioCap, targetWidth, targetHeight, trace_id); })); } @@ -551,7 +682,7 @@ Dart_Handle SingleFrameCodec::getNextFrame(Dart_Handle callback_handle) { void Codec::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({ - {"instantiateImageCodec", InstantiateImageCodec, 4, true}, + {"instantiateImageCodec", InstantiateImageCodec, 6, true}, }); natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } diff --git a/engine/src/flutter/testing/dart/image_resize_test.dart b/engine/src/flutter/testing/dart/image_resize_test.dart new file mode 100644 index 0000000000..5976fab97f --- /dev/null +++ b/engine/src/flutter/testing/dart/image_resize_test.dart @@ -0,0 +1,128 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; +import 'dart:ui'; + +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +void main() { + test('no resize by default', () async { + final Uint8List bytes = await readFile('4x4.png'); + final Codec codec = await instantiateImageCodec(bytes); + final FrameInfo frame = await codec.getNextFrame(); + final int codecHeight = frame.image.height; + final int codecWidth = frame.image.width; + expect(codecHeight, 2); + expect(codecWidth, 2); + }); + + test('resize width with constrained height', () async { + final Uint8List bytes = await readFile('4x4.png'); + final Codec codec = await instantiateImageCodec(bytes, targetHeight: 1); + final FrameInfo frame = await codec.getNextFrame(); + final int codecHeight = frame.image.height; + final int codecWidth = frame.image.width; + expect(codecHeight, 1); + expect(codecWidth, 1); + }); + + test('resize height with constrained width', () async { + final Uint8List bytes = await readFile('4x4.png'); + final Codec codec = await instantiateImageCodec(bytes, targetWidth: 1); + final FrameInfo frame = await codec.getNextFrame(); + final int codecHeight = frame.image.height; + final int codecWidth = frame.image.width; + expect(codecHeight, 1); + expect(codecWidth, 1); + }); + + test('upscale image by 5x', () async { + final Uint8List bytes = await readFile('4x4.png'); + final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10); + final FrameInfo frame = await codec.getNextFrame(); + final int codecHeight = frame.image.height; + final int codecWidth = frame.image.width; + expect(codecHeight, 10); + expect(codecWidth, 10); + }); + + test('upscale image varying width and height', () async { + final Uint8List bytes = await readFile('4x4.png'); + final Codec codec = + await instantiateImageCodec(bytes, targetWidth: 10, targetHeight: 1); + final FrameInfo frame = await codec.getNextFrame(); + final int codecHeight = frame.image.height; + final int codecWidth = frame.image.width; + expect(codecHeight, 1); + expect(codecWidth, 10); + }); + + test('pixels: no resize by default', () async { + final BlackSquare blackSquare = BlackSquare.create(); + final Image resized = await blackSquare.resize(); + expect(resized.height, blackSquare.height); + expect(resized.width, blackSquare.width); + }); + + test('pixels: resize width with constrained height', () async { + final BlackSquare blackSquare = BlackSquare.create(); + final Image resized = await blackSquare.resize(targetHeight: 1); + expect(resized.height, 1); + expect(resized.width, 1); + }); + + test('pixels: resize height with constrained width', () async { + final BlackSquare blackSquare = BlackSquare.create(); + final Image resized = await blackSquare.resize(targetWidth: 1); + expect(resized.height, 1); + expect(resized.width, 1); + }); + + test('pixels: upscale image by 5x', () async { + final BlackSquare blackSquare = BlackSquare.create(); + final Image resized = await blackSquare.resize(targetWidth: 10); + expect(resized.height, 10); + expect(resized.width, 10); + }); + + test('pixels: upscale image varying width and height', () async { + final BlackSquare blackSquare = BlackSquare.create(); + final Image resized = + await blackSquare.resize(targetHeight: 1, targetWidth: 10); + expect(resized.height, 1); + expect(resized.width, 10); + }); +} + +class BlackSquare { + BlackSquare._(this.width, this.height, this.pixels); + + factory BlackSquare.create({int width = 2, int height = 2}) { + final Uint8List pixels = + Uint8List.fromList(List.filled(width * height * 4, 0)); + return BlackSquare._(width, height, pixels); + } + + Future resize({int targetWidth, int targetHeight}) async { + final Completer imageCompleter = Completer(); + decodeImageFromPixels(pixels, width, height, PixelFormat.rgba8888, + (Image image) => imageCompleter.complete(image), + targetHeight: targetHeight, targetWidth: targetWidth); + return await imageCompleter.future; + } + + final int width; + final int height; + final Uint8List pixels; +} + +Future readFile(String fileName) async { + final File file = + File(path.join('flutter', 'testing', 'resources', fileName)); + return await file.readAsBytes(); +}