Search code examples
androidflutterimagedart

How to convert image to line art - flutter


I have an app which let users draw image with camera by showing image on CameraPreview widget with less opacity so user can trace the image anywhere.

When user select an image from gallery I want to let them create it into line art where only line or strokes of the image is visible and the background of the image is transparent. Something like this.

image of a Porsche 911

I have tried to find how to do this and I found ImageFilter widget which did not help.

Please help me, Thank you.


Solution

  • Try this code:

    import 'package:flutter/material.dart';
    import 'package:image/image.dart' as img;
    import 'package:flutter/services.dart';
    
    
    class TransparentImage extends StatefulWidget {
      @override
      _TransparentImageState createState() => _TransparentImageState();
    }
    
    class _TransparentImageState extends State<TransparentImage> {
      Uint8List? Converted_Image;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(color: Colors.black,
            child:Column(mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Converted_Image == null
                ? CircularProgressIndicator()
                  : Image.memory(Converted_Image!)
              ],
            ),
          ),
        );
      }
    
      @override
      void initState() {
        super.initState();
        ConvertImage();
      }
    
      Future<void> ConvertImage() async {
        final ByteData data = await rootBundle.load('assets/test.png');
        final List<int> bytes = data.buffer.asUint8List();
    
        img.Image originalImage = img.decodeImage(Uint8List.fromList(bytes))!;
    
        img.Image grayscaleImage = img.grayscale(originalImage);
    
        img.Image edgeDetectedImage = img.sobel(grayscaleImage);
    
        img.Image invertedImage = img.invert(edgeDetectedImage);
    
        Uint8List sketchBytes = Uint8List.fromList(img.encodeJpg(invertedImage));
    
        setState(() {
          Converted_Image = sketchBytes;
        });
      }
    }