diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index 96af472629..c08d3cf46f 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -1196,6 +1196,38 @@ class Paint { } } +/// The format in which image bytes should be returned when using +/// [Image.toByteData]. +enum ImageByteFormat { + /// Raw RGBA format. + /// + /// Unencoded bytes, in RGBA row-primary form, 8 bits per channel. + rawRgba, + + /// Raw unmodified format. + /// + /// Unencoded bytes, in the image's existing format. For example, a grayscale + /// image may use a single 8-bit channel for each pixel. + rawUnmodified, + + /// PNG format. + /// + /// A loss-less compression format for images. This format is well suited for + /// images with hard edges, such as screenshots or sprites, and images with + /// text. Transparency is supported. The PNG format supports images up to + /// 2,147,483,647 pixels in either dimension, though in practice available + /// memory provides a more immediate limitation on maximum image size. + /// + /// PNG images normally use the `.png` file extension and the `image/png` MIME + /// type. + /// + /// See also: + /// + /// * , the Wikipedia page on PNG. + /// * , the PNG standard. + png, +} + /// Opaque handle to raw decoded image data (pixels). /// /// To obtain an [Image] object, use [instantiateImageCodec]. @@ -1217,20 +1249,21 @@ class Image extends NativeFieldWrapperClass2 { /// Converts the [Image] object into a byte array. /// - /// The image bytes will be RGBA form, 8 bits per channel, row-primary. + /// The [format] argument specifies the format in which the bytes will be + /// returned. /// /// Returns a future that completes with the binary image data or an error /// if encoding fails. - Future toByteData() { + Future toByteData({ImageByteFormat format: ImageByteFormat.rawRgba}) { return _futurize((_Callback callback) { - return _toByteData((Uint8List encoded) { + return _toByteData(format.index, (Uint8List encoded) { callback(encoded?.buffer?.asByteData()); }); }); } /// Returns an error message on failure, null on success. - String _toByteData(_Callback callback) native 'Image_toByteData'; + String _toByteData(int format, _Callback callback) native 'Image_toByteData'; /// Release the resources used by this object. The object is no longer usable /// after this method is called. @@ -1530,8 +1563,8 @@ class Path extends NativeFieldWrapperClass2 { /// Adds a new subpath that consists of a curve that forms the /// ellipse that fills the given rectangle. - /// - /// To add a circle, pass an appropriate rectangle as `oval`. [Rect.fromCircle] + /// + /// To add a circle, pass an appropriate rectangle as `oval`. [Rect.fromCircle] /// can be used to easily describe the circle's center [Offset] and radius. void addOval(Rect oval) { assert(_rectIsValid(oval)); @@ -1938,8 +1971,8 @@ class Gradient extends Shader { /// If `center`, `radius`, `colors`, or `tileMode` are null, or if `colors` or /// `colorStops` contain null values, this constructor will throw a /// [NoSuchMethodError]. - /// - /// If `matrix4` is provided, the gradient fill will be transformed by the + /// + /// If `matrix4` is provided, the gradient fill will be transformed by the /// specified 4x4 matrix relative to the local coordinate system. `matrix4` must /// be a column-major matrix packed into a list of 16 values. Gradient.radial( @@ -2917,11 +2950,11 @@ typedef String _Callbacker(_Callback callback); /// /// ```dart /// typedef void IntCallback(int result); -/// +/// /// String _doSomethingAndCallback(IntCallback callback) { /// new Timer(new Duration(seconds: 1), () { callback(1); }); /// } -/// +/// /// Future doSomething() { /// return _futurize(_doSomethingAndCallback); /// } diff --git a/engine/src/flutter/lib/ui/painting/image.cc b/engine/src/flutter/lib/ui/painting/image.cc index 4704a9ae66..ef45856230 100644 --- a/engine/src/flutter/lib/ui/painting/image.cc +++ b/engine/src/flutter/lib/ui/painting/image.cc @@ -32,8 +32,8 @@ CanvasImage::CanvasImage() = default; CanvasImage::~CanvasImage() = default; -Dart_Handle CanvasImage::toByteData(Dart_Handle callback) { - return GetImageBytes(this, callback); +Dart_Handle CanvasImage::toByteData(int format, Dart_Handle callback) { + return EncodeImage(this, format, callback); } void CanvasImage::dispose() { diff --git a/engine/src/flutter/lib/ui/painting/image.h b/engine/src/flutter/lib/ui/painting/image.h index 3c6620fda2..e92db979ed 100644 --- a/engine/src/flutter/lib/ui/painting/image.h +++ b/engine/src/flutter/lib/ui/painting/image.h @@ -31,7 +31,7 @@ class CanvasImage final : public fxl::RefCountedThreadSafe, int height() { return image_.get()->height(); } - Dart_Handle toByteData(Dart_Handle callback); + Dart_Handle toByteData(int format, Dart_Handle callback); void dispose(); diff --git a/engine/src/flutter/lib/ui/painting/image_encoding.cc b/engine/src/flutter/lib/ui/painting/image_encoding.cc index c103d5d827..6de40034d7 100644 --- a/engine/src/flutter/lib/ui/painting/image_encoding.cc +++ b/engine/src/flutter/lib/ui/painting/image_encoding.cc @@ -31,6 +31,13 @@ using tonic::ToDart; namespace blink { namespace { +// This must be kept in sync with the enum in painting.dart +enum ImageByteFormat { + kRawRGBA, + kRawUnmodified, + kPNG, +}; + void InvokeDataCallback(std::unique_ptr callback, sk_sp buffer) { tonic::DartState* dart_state = callback->dart_state().get(); @@ -47,13 +54,17 @@ void InvokeDataCallback(std::unique_ptr callback, } } -sk_sp GetImageBytesAsRGBA(sk_sp image) { +sk_sp EncodeImage(sk_sp image, ImageByteFormat format) { TRACE_EVENT0("flutter", __FUNCTION__); if (image == nullptr) { return nullptr; } + if (format == kPNG) { + return image->encodeToData(SkEncodedImageFormat::kPNG, 0); + } + // Copy the GPU image snapshot into CPU memory. auto cpu_snapshot = image->makeRasterImage(); if (!cpu_snapshot) { @@ -67,6 +78,11 @@ sk_sp GetImageBytesAsRGBA(sk_sp image) { return nullptr; } + if (format == kRawUnmodified) { + return SkData::MakeWithCopy(pixmap.addr(), pixmap.computeByteSize()); + } + + ASSERT(format == kRawRGBA); if (pixmap.colorType() != kRGBA_8888_SkColorType) { TRACE_EVENT0("flutter", "ConvertToRGBA"); @@ -80,36 +96,38 @@ sk_sp GetImageBytesAsRGBA(sk_sp image) { return nullptr; } - const size_t pixmap_size = pixmap.computeByteSize(); - return SkData::MakeWithCopy(pixmap.addr32(), pixmap_size); + return SkData::MakeWithCopy(pixmap.addr32(), pixmap.computeByteSize()); } else { - const size_t pixmap_size = pixmap.computeByteSize(); - return SkData::MakeWithCopy(pixmap.addr32(), pixmap_size); + return SkData::MakeWithCopy(pixmap.addr32(), pixmap.computeByteSize()); } } -void GetImageBytesAndInvokeDataCallback( +void EncodeImageAndInvokeDataCallback( std::unique_ptr callback, sk_sp image, - fxl::RefPtr ui_task_runner) { - sk_sp buffer = GetImageBytesAsRGBA(std::move(image)); + fxl::RefPtr ui_task_runner, + ImageByteFormat format) { + sk_sp encoded = EncodeImage(std::move(image), format); ui_task_runner->PostTask( - fxl::MakeCopyable([callback = std::move(callback), buffer]() mutable { - InvokeDataCallback(std::move(callback), std::move(buffer)); + fxl::MakeCopyable([callback = std::move(callback), encoded]() mutable { + InvokeDataCallback(std::move(callback), std::move(encoded)); })); } } // namespace -Dart_Handle GetImageBytes(CanvasImage* canvas_image, - Dart_Handle callback_handle) { +Dart_Handle EncodeImage(CanvasImage* canvas_image, + int format, + Dart_Handle callback_handle) { if (!canvas_image) return ToDart("encode called with non-genuine Image."); if (!Dart_IsClosure(callback_handle)) return ToDart("Callback must be a function."); + ImageByteFormat image_format = static_cast(format); + auto callback = std::make_unique( tonic::DartState::Current(), callback_handle); sk_sp image = canvas_image->image(); @@ -118,10 +136,12 @@ Dart_Handle GetImageBytes(CanvasImage* canvas_image, task_runners.GetIOTaskRunner()->PostTask(fxl::MakeCopyable( [callback = std::move(callback), image, - ui_task_runner = task_runners.GetUITaskRunner()]() mutable { - GetImageBytesAndInvokeDataCallback(std::move(callback), - std::move(image), - std::move(ui_task_runner)); + ui_task_runner = task_runners.GetUITaskRunner(), + image_format]() mutable { + EncodeImageAndInvokeDataCallback(std::move(callback), + std::move(image), + std::move(ui_task_runner), + image_format); })); return Dart_Null(); diff --git a/engine/src/flutter/lib/ui/painting/image_encoding.h b/engine/src/flutter/lib/ui/painting/image_encoding.h index 5081bc4ee5..2f7618db98 100644 --- a/engine/src/flutter/lib/ui/painting/image_encoding.h +++ b/engine/src/flutter/lib/ui/painting/image_encoding.h @@ -11,8 +11,9 @@ namespace blink { class CanvasImage; -Dart_Handle GetImageBytes(CanvasImage* canvas_image, - Dart_Handle callback_handle); +Dart_Handle EncodeImage(CanvasImage* canvas_image, + int format, + Dart_Handle callback_handle); } // namespace blink diff --git a/engine/src/flutter/testing/dart/encoding_test.dart b/engine/src/flutter/testing/dart/encoding_test.dart index 27b71dc478..c8210d9b4e 100644 --- a/engine/src/flutter/testing/dart/encoding_test.dart +++ b/engine/src/flutter/testing/dart/encoding_test.dart @@ -18,71 +18,115 @@ const Color _kGreen = const Color.fromRGBO(0, 255, 0, 1.0); void main() { group('Image.toByteData', () { - test('Encode with default arguments', () async { - Image testImage = createSquareTestImage(); - ByteData data = await testImage.toByteData(); - expect(new Uint8List.view(data.buffer), getExpectedBytes()); + group('RGBA format', () { + test('works with simple image', () async { + ByteData data = await Square4x4Image.image.toByteData(); + expect(new Uint8List.view(data.buffer), Square4x4Image.bytes); + }); + + test('converts grayscale images', () async { + Image image = await GrayscaleImage.load(); + ByteData data = await image.toByteData(); + Uint8List bytes = data.buffer.asUint8List(); + expect(bytes, hasLength(16)); + expect(bytes, GrayscaleImage.bytesAsRgba); + }); }); - test('Handles grayscale images', () async { - File grayscaleImage = new File(path.join('flutter', 'testing', 'resources', '4x4.png')); - Uint8List png = await grayscaleImage.readAsBytes(); - Completer completer = new Completer(); - decodeImageFromList(png, (Image image) => completer.complete(image)); - Image image = await completer.future; - ByteData data = await image.toByteData(); - Uint8List bytes = data.buffer.asUint8List(); - expect(bytes, hasLength(16)); - expect(bytes, [ - 255, 255, 255, 255, - 127, 127, 127, 255, - 127, 127, 127, 255, - 0, 0, 0, 255, - ]); + group('Unmodified format', () { + test('works with simple image', () async { + Image image = Square4x4Image.image; + ByteData data = await image.toByteData(format: ImageByteFormat.rawUnmodified); + expect(new Uint8List.view(data.buffer), Square4x4Image.bytes); + }); + + test('works with grayscale images', () async { + Image image = await GrayscaleImage.load(); + ByteData data = await image.toByteData(format: ImageByteFormat.rawUnmodified); + Uint8List bytes = data.buffer.asUint8List(); + expect(bytes, hasLength(4)); + expect(bytes, GrayscaleImage.bytesUnmodified); + }); + }); + + group('PNG format', () { + test('works with simple image', () async { + Image image = Square4x4Image.image; + ByteData data = await image.toByteData(format: ImageByteFormat.png); + List expected = await readFile('square.png'); + expect(new Uint8List.view(data.buffer), expected); + }); }); }); } -Image createSquareTestImage() { - double width = _kWidth.toDouble(); - double radius = _kRadius.toDouble(); - double innerWidth = (_kWidth - 2 * _kRadius).toDouble(); +class Square4x4Image { + static Image get image { + double width = _kWidth.toDouble(); + double radius = _kRadius.toDouble(); + double innerWidth = (_kWidth - 2 * _kRadius).toDouble(); - PictureRecorder recorder = new PictureRecorder(); - Canvas canvas = - new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, width, width)); + PictureRecorder recorder = new PictureRecorder(); + Canvas canvas = + new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, width, width)); - Paint black = new Paint() - ..strokeWidth = 1.0 - ..color = _kBlack; - Paint green = new Paint() - ..strokeWidth = 1.0 - ..color = _kGreen; + Paint black = new Paint() + ..strokeWidth = 1.0 + ..color = _kBlack; + Paint green = new Paint() + ..strokeWidth = 1.0 + ..color = _kGreen; - canvas.drawRect(new Rect.fromLTWH(0.0, 0.0, width, width), black); - canvas.drawRect( - new Rect.fromLTWH(radius, radius, innerWidth, innerWidth), green); - return recorder.endRecording().toImage(_kWidth, _kWidth); -} - -List getExpectedBytes() { - int bytesPerChannel = 4; - List result = new List(_kWidth * _kWidth * bytesPerChannel); - - fillWithColor(Color color, int min, int max) { - for (int i = min; i < max; i++) { - for (int j = min; j < max; j++) { - int offset = i * bytesPerChannel + j * _kWidth * bytesPerChannel; - result[offset] = color.red; - result[offset + 1] = color.green; - result[offset + 2] = color.blue; - result[offset + 3] = color.alpha; - } - } + canvas.drawRect(new Rect.fromLTWH(0.0, 0.0, width, width), black); + canvas.drawRect( + new Rect.fromLTWH(radius, radius, innerWidth, innerWidth), green); + return recorder.endRecording().toImage(_kWidth, _kWidth); } - fillWithColor(_kBlack, 0, _kWidth); - fillWithColor(_kGreen, _kRadius, _kWidth - _kRadius); + static List get bytes { + int bytesPerChannel = 4; + List result = new List(_kWidth * _kWidth * bytesPerChannel); - return result; + fillWithColor(Color color, int min, int max) { + for (int i = min; i < max; i++) { + for (int j = min; j < max; j++) { + int offset = i * bytesPerChannel + j * _kWidth * bytesPerChannel; + result[offset] = color.red; + result[offset + 1] = color.green; + result[offset + 2] = color.blue; + result[offset + 3] = color.alpha; + } + } + } + + fillWithColor(_kBlack, 0, _kWidth); + fillWithColor(_kGreen, _kRadius, _kWidth - _kRadius); + + return result; + } +} + +class GrayscaleImage { + static Future load() async { + Uint8List bytes = await readFile('4x4.png'); + Completer completer = new Completer(); + decodeImageFromList(bytes, (Image image) => completer.complete(image)); + return await completer.future; + } + + static List get bytesAsRgba { + return [ + 255, 255, 255, 255, + 127, 127, 127, 255, + 127, 127, 127, 255, + 0, 0, 0, 255, + ]; + } + + static List get bytesUnmodified => [255, 127, 127, 0]; +} + +Future readFile(fileName) async { + final file = new File(path.join('flutter', 'testing', 'resources', fileName)); + return await file.readAsBytes(); } diff --git a/engine/src/flutter/testing/resources/square.png b/engine/src/flutter/testing/resources/square.png new file mode 100644 index 0000000000..a042cece55 Binary files /dev/null and b/engine/src/flutter/testing/resources/square.png differ