Home > Net >  Flutter convert ui.Image to a file
Flutter convert ui.Image to a file

Time:10-18

The code:

final tempDir = await getApplicationDocumentsDirectory();
            File file = File("${tempDir.path}/image.png");

            ui.Image croppedImage = await cropController.croppedBitmap();

            final data = await croppedImage.toByteData(
              format: ui.ImageByteFormat.png,
            );

            final bytes = data.buffer.asUint64List();

            file = await file.writeAsBytes(bytes, flush: true);

The cropController is from the crop_image plugin.

I get this error when I posted Image.file

The following _Exception was thrown resolving an image codec:
Exception: Invalid image data

What am I doing wrong?

CodePudding user response:

You want a Uint8List, not a Uint64List. writeAsBytes is truncating your 64-bit ints to 8-bit ints and you're losing 3/4 of the data.

Change

final bytes = data.buffer.asUint64List();

to

final bytes = data.buffer.asUint8List();
  • Related