Creating raw image from Widget or Canvas
My end goal is to be able to share a dynamic image by either passing the raw image data or saving the image to disk for a native android/ios service to share. How would I convert a Widget
or Canvas
in flutter to raw image data (like byte[]
)?
Solution 1:
There is support for this now. You can either use RenderRepaintBoundry
or OffsetLayer
or Scene
. They all have a toImage
. Here is the link to RenderRepaintBoundry.toImage()
Future<void> _capturePng() async {
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
}
This is copied from the docs.
Solution 2:
This is not currently possible from Dart code running in a FlutterView today, however we have a bug on file tracking implementing such: https://github.com/flutter/flutter/issues/6774
It is possible to render Flutter widgets as part of a FlutterView and then use Java or Objective-C interfaces onto the FlutterView to capture a picture, such as the standard android.View.getBitmap which FlutterView implements: https://docs.flutter.io/javadoc/io/flutter/view/FlutterView.html#getBitmap--
If this important to your application needs and would like to be able to capture Bitmaps of Widget trees from inside Dart code we'd love to hear about it. Please feel encouraged to provide further context on the above referenced issue!
Solution 3:
You can use the Screenshot package
to get an image
of the widget
you want.
https://pub.dev/packages/screenshot