Flutter: How would one save a Canvas/CustomPainter to an image file?

前端 未结 2 397
时光说笑
时光说笑 2020-12-15 07:58

I am trying to collect a signature from the user and save it to an image. I have made it far enough that I can draw on the screen, but now I\'d like to click a button to sav

相关标签:
2条回答
  • 2020-12-15 08:15

    Add the rendered method in your widget

      ui.Image get rendered {
        // [CustomPainter] has its own @canvas to pass our
        // [ui.PictureRecorder] object must be passed to [Canvas]#contructor
        // to capture the Image. This way we can pass @recorder to [Canvas]#contructor
        // using @painter[SignaturePainter] we can call [SignaturePainter]#paint
        // with the our newly created @canvas
        ui.PictureRecorder recorder = ui.PictureRecorder();
        Canvas canvas = Canvas(recorder);
        SignaturePainter painter = SignaturePainter(points: _points);
        var size = context.size;
        painter.paint(canvas, size);
        return recorder.endRecording()
            .toImage(size.width.floor(), size.height.floor());
      }
    

    Then using state fetch the rendered image

    var image = signatureKey.currentState.rendered
    

    Now, you can produce png Image using toByteData(format: ui.ImageByteFormat.png) and store using asInt8List()

    var pngBytes = await image.toByteData(format: ui.ImageByteFormat.png)
    File('your-path/filename.png')
        .writeAsBytesSync(pngBytes.buffer.asInt8List())
    

    For complete example, on how to export canvas as png check out this example https://github.com/vemarav/signature

    0 讨论(0)
  • 2020-12-15 08:22

    You can capture the output of a CustomPainter with PictureRecorder. Pass your PictureRecorder instance to the constructor for your Canvas. The Picture returned by PictureRecorder.endRecording can then be converted to an Image with Picture.toImage. Finally, extract the image bytes using Image.toByteData.

    Here's an example: https://github.com/rxlabz/flutter_canvas_to_image

    0 讨论(0)
提交回复
热议问题