Search code examples
imageflutterdartscreenshot

Flutter- how to get pictures of screen widgets?


I am making a face in flutter using different facial images and i want to export it as jpg when the face creation is done. what could i use to achieve it?

enter image description here

You can see here a face is created and i want to export only face as a jpeg.


Solution

  • In this article, use GlobalKey with your widget and save image by following code:

    takeScreenShot() async {
      RenderRepaintBoundary boundary =
          previewContainer.currentContext.findRenderObject();
      double pixelRatio = originalSize / MediaQuery.of(context).size.width;
      ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
      ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      setState(() {
        _image2 = Image.memory(pngBytes.buffer.asUint8List());
      });
      final directory = (await getApplicationDocumentsDirectory()).path;
      File imgFile = new File('$directory/screenshot.png');
      imgFile.writeAsBytes(pngBytes);
      final snackBar = SnackBar(
        content: Text('Saved to ${directory}'),
        action: SnackBarAction(
          label: 'Ok',
          onPressed: () {
            // Some code
          },
        ),
      );
    
      Scaffold.of(context).showSnackBar(snackBar);
    }