4

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.
Chheangly Prum
  • 145
  • 2
  • 2
  • 10

3 Answers3

7

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.

Vinoth Vino
  • 9,166
  • 3
  • 66
  • 70
2

simply use this method

var bytes = await File('filename').readAsBytes();
Vinoth Vino
  • 9,166
  • 3
  • 66
  • 70
Muhammad Noman
  • 1,344
  • 1
  • 14
  • 28
1

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!