Mudassir
Mudassir

Reputation: 806

Flutter convert ui.Image to a file

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?

Upvotes: 0

Views: 2967

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17113

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();

Upvotes: 3

Related Questions