Flutter: how to export/save a CustomPainter draw to a string coordinates or image base64?
273
Add a Image and listem to the CustomPaiter you made, then gets the render and convert it to a base64 string
for example:
// getter canvas to image
Future<ui.Image> get rendered {
var size = context.size;
ui.PictureRecorder recorder = ui.PictureRecorder();
Canvas canvas = Canvas(recorder);
Signature= Signature(points: _points);
painter.paint(canvas, size);
return recorder.endRecording().toImage(size.width.floor(), size.height.floor());
}
// function to convert to String
Future<String> convertCanvasToB64() async {
final img = await rendered;
final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
final imgBase64 = base64.encode(pngBytes!.buffer.asUint8List());
return imgBase64;
}
Author by
Ali Briceño
Developer ReactJS | Angular | Javascript and Design is my passion!
Updated on December 20, 2022Comments
-
Ali Briceño over 1 year
I have a CustomPainter where the user must draw multiples lines pointing various things on a image. I need export all these lines to a array of strings or image base64. Is this possible? My code is like:
class Signature extends CustomPainter { List<Offset> points; Signature({this.points}); @override 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); } canvas.clipRect(Offset.zero & size); } } @override bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points; }
-
Ali Briceño over 2 yearsThanks a lot for this solution!