flutter-ml / google_ml_kit_flutter

A flutter plugin that implements Google's standalone ML Kit
MIT License
952 stars 727 forks source link

Convert InputImage to Base64 #594

Open hendry456 opened 6 months ago

hendry456 commented 6 months ago

Hi, i want to thank you for this library, it is really useful for me. One thing i want to ask is, can i get the Base64 version from the InputImage object?

i tried this code

String inputImageToBase64(InputImage inputImage) {
  // Get image byte data
  final byteData = inputImage.bytes;
  if (byteData == null) {
    throw Exception("Failed to get byte data from InputImage");
  }
  final imageData = byteData.buffer.asUint8List();

  // Encode image byte data to Base64
  final base64Image = base64Encode(imageData);

  return base64Image;
}

but it seems like it didn't gave me the right Base64, i couldn't process it in my api server.

i searched in every website but i couldn't find the solution. Or am i missing something somewhere in the process? Any help is appreciated. Thank you!

scognito commented 3 weeks ago

This is not a bug, anyway I use this code and it works:

Future<String?> convertImageToBase64(Image image) async {
    try {
      // Step 1: Convert the image to an ImageProvider (assuming AssetImage or NetworkImage)
      final ImageProvider imageProvider = image.image;

      // Step 2: Resolve the image and obtain a ImageStream
      final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
      final Completer<ui.Image> completer = Completer<ui.Image>();

      // Step 3: Add a listener to get the image once it is available
      stream.addListener(ImageStreamListener((ImageInfo info, bool _) {
        completer.complete(info.image);
      }));

      // Step 4: Wait for the image to be loaded
      final ui.Image loadedImage = await completer.future;

      // Step 5: Convert the ui.Image to byte data
      final ByteData? byteData = await loadedImage.toByteData(format: ui.ImageByteFormat.png);

      if (byteData != null) {
        // Step 6: Convert the byte data to Uint8List
        final Uint8List uint8List = byteData.buffer.asUint8List();

        // Step 7: Convert the Uint8List to Base64 string
        String base64String = base64Encode(uint8List);

        return base64String;
      }
    } catch (e) {
      debugPrint('Error converting image to base64: $e');
    }
    return null;
  }