Search code examples
flutterimageflutter-web

Flutter Web - Save ui.Image to png File


I need some help with my code, I use the

"FilePicker.platform.saveFile()"

function to get the path on Windows Version (but not works on Web) and then

"final imageFuture = await controller
          .renderImage(backgroundImageSize)
          .then<Uint8List?>((ui.Image image) => image.pngBytes);
final imgFile = File(path);
imgFile.writeAsBytesSync(imageFuture!);
"

to save my image to disk, this works perfectly on Windows, but not on the web version.
I need an alternative to save ui.Image (web Version) to PNG File on disk. 🙏🙏


Solution

  • I was able to solve my problem only, however the solution works only in release mode (after the build process).

    import 'dart:html' as html;
    import 'dart:js' as js;
    
    final backgroundImageSize = Size(backgroundImage!.width.toDouble(),
              backgroundImage!.height.toDouble());
          final imageFuture = await controller
              .renderImage(backgroundImageSize)
              .then<Uint8List?>((ui.Image image) => image.pngBytes);
    (imageFuture != null)
            ? js.context.callMethod(
                "saveAs",
                [
                  html.Blob([imageFuture]),
                  'output-image.png',
                ],
              )
            : print('Image is null');
    

    It is necessary to add inside your web/index.html file:

    <script  src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>