Chheangly Prum
Chheangly Prum

Reputation: 185

Flutter convert image to binary data

How can i covert Image file to binary data ? I'm using a library call image_picker for pick the image from gallery or camera. And I want to convert the image that I picked to binary data.

File image = await ImagePicker.pickImage(source: ImageSource.gallery)
(image as Image).toByteData // the method toByteData here is not pop up.

Upvotes: 7

Views: 20914

Answers (4)

Andrii Syrokomskyi
Andrii Syrokomskyi

Reputation: 423

Try this package:

final pngBytes = image.pngUint8List;

or

final bmpBytes = image.bmpUint8List;

Upvotes: 0

Vinoth
Vinoth

Reputation: 9734

toByteData() method allows converting the image into a byte array. We need to pass the format in the format argument which specifies the format in which the bytes will be returned. It'll return the future that completes with binary data or error.

final pngByteData = await image.toByteData(format: ImageByteFormat.png);

ImageByteFormat enum contains the following constants.

  • png
  • rawRgba
  • rawUnmodified
  • values

For more information about ImageByteFormat, please have a look at this documentation.

Update : If you want to convert the image file into bytes. Then use readAsByte() method.

var bytes = await ImagePicker.pickImage(source: ImageSource.gallery).readAsBytes();

For converting image into a file, Check out this answer.

Upvotes: 10

Muhammad Noman
Muhammad Noman

Reputation: 1366

simply use this method

var bytes = await File('filename').readAsBytes();

Upvotes: 2

Anakin Skywalker
Anakin Skywalker

Reputation: 41

You might want to consider using the toByteData method. It converts an image object into an array of bytes. It returns a future which returns a binary image data or an error if the encoding fails. Here is the implementation from this website: https://api.flutter.dev/flutter/dart-ui/Image/toByteData.html

Future<ByteData> toByteData({ImageByteFormat format = ImageByteFormat.rawRgba}) {
  return _futurize((_Callback<ByteData> callback) {
    return _toByteData(format.index, (Uint8List encoded) {
      callback(encoded?.buffer?.asByteData());
    });
  });
}

The format argument specifies in which encoding format the bytes will be returned in. Hope this helps!

Upvotes: 1

Related Questions