0

I'm developing a feature in a Flutter application where users can capture a photo using the camera package. After capture, the image is displayed on the screen, allowing users to draw lines and points on it using CustomPaint. The problem arises when saving the image with the drawings: the base image is saved correctly, but the drawn lines and points appear distorted, specifically shortened and shifted upwards.

Function to save:

Future<void> _saveUpdatedImage() async {
 try {
 /// PNG
 ///
 final recorder = ui.PictureRecorder();
 final canvas = Canvas(recorder);
 final image = File(widget.imagePath);
 final ui.Image decodedImage = await decodeImageFromFile(image);
 // Draw the image first:
 canvas.drawImage(decodedImage, Offset.zero, Paint());
 // Then draw the painter on top:
 final painter = DrawingPainter(_points, _lines);
 painter.paint(canvas,
 Size(decodedImage.width.toDouble(), decodedImage.height.toDouble()));
 final picture = recorder.endRecording();
 final ui.Image updatedImage =
 await picture.toImage(decodedImage.width, decodedImage.height);
 final byteData =
 await updatedImage.toByteData(format: ui.ImageByteFormat.png);
 final pngBytes = byteData!.buffer.asUint8List();
 final file = File(widget.imagePath);
 await file.writeAsBytes(pngBytes);
 ScaffoldMessenger.of(context).showSnackBar(
 SnackBar(content: Text('Image updated and saved!')),
 );
 } catch (e) {
 print('Error saving image: $e');
 ScaffoldMessenger.of(context).showSnackBar(
 SnackBar(content: Text('Error saving image!')),
 );
 }
 }

Custom Painter

class DrawingPainter extends CustomPainter {
 final List<Offset> points;
 final List<List<Offset>> lines;
 DrawingPainter(this.points, this.lines);
 @override
 void paint(Canvas canvas, Size size) {
 final pointPaint = Paint()
 ..color = Colors.red
 ..strokeWidth = 5.0;
 final linePaint = Paint()
 ..color = Colors.blue
 ..strokeWidth = 3.0
 ..style = PaintingStyle.stroke;
 for (final point in points) {
 canvas.drawPoints(PointMode.points, [point], pointPaint);
 }
 for (final line in lines) {
 if (line.isNotEmpty) {
 for (int i = 0; i < line.length - 1; i++) {
 canvas.drawLine(line[i], line[i + 1], linePaint);
 }
 }
 }
 }
 @override
 bool shouldRepaint(covariant CustomPainter oldDelegate) {
 return true;
 }
}

The first line is after saved and second line is the origin line when user draw. Print saved image

asked Mar 12, 2025 at 1:01

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.