Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 save to an image and store in my database.

This is what I have so far:

import 'package:flutter/material.dart';  class SignaturePadPage extends StatefulWidget {   SignaturePadPage({Key key}) : super(key: key);    @override   _SignaturePadPage createState() => new _SignaturePadPage(); } class _SignaturePadPage extends State<SignaturePadPage> {    List<Offset> _points = <Offset>[];    @override   Widget build(BuildContext context) {     return Container(       color: Colors.white,       child: GestureDetector(         onPanUpdate: (DragUpdateDetails details) {           setState(() {             RenderBox referenceBox = context.findRenderObject();             Offset localPosition =             referenceBox.globalToLocal(details.globalPosition);             _points = new List.from(_points)..add(localPosition);           });         },         onPanEnd: (DragEndDetails details) => _points.add(null),         child: new CustomPaint(painter: new SignaturePainter(_points)),       ),     );   } }  class SignaturePainter extends CustomPainter {   SignaturePainter(this.points);   final List<Offset> points;   void paint(Canvas canvas, Size size) {     Paint paint = new Paint()       ..color = Colors.black       ..strokeCap = StrokeCap.round       ..strokeWidth = 5.0;     for (int i = 0; i < points.length - 1; i++) {       if (points[i] != null && points[i + 1] != null)         canvas.drawLine(points[i], points[i + 1], paint);     }   }   bool shouldRepaint(SignaturePainter other) => other.points != points; } 

Not sure where to go from there...

like image 824
Jus10 Avatar asked May 13 '18 20:05

Jus10


People also ask

How do you save a canvas as an image in Flutter?

Saving Image to GalleryThe FAB's onPressed() method calls the asynchronous _save() method to save the current state of canvas as image to gallery.

How do I store image path in Flutter?

// using your method of getting an image final File image = await ImagePicker. pickImage(source: imageSource); // getting a directory path for saving final String path = await getApplicationDocumentsDirectory(). path; // copy the file to a new path final File newImage = await image. copy('$path/image1.


1 Answers

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

like image 70
jspcal Avatar answered Sep 23 '22 07:09

jspcal