1

I am using the flutter camera plugin to take pictures from my app using the camera device and send them as base64 images on the server.

When I want to convert the generated image into a base 64 image I can perfectly do it from my android emulator with this line :

base64img = base64Encode(File(image.path).readAsBytesSync());

"image" is a XFile. "image.path" is a String.

When I try to use the same line on the web I get this error :

Exception caught by gesture ═══════════════════════════════════════════ The following UnsupportedError was thrown while handling a gesture: Unsupported operation: _Namespace

I tried with this line (directly trying to convert the XFile instead of converting a generated File from the image path String) :

base64img = base64Encode(image.readAsBytesSync())

I get the same error.

Thanks for helping.

JS1
  • 631
  • 2
  • 7
  • 23

2 Answers2

2

Found the solution, using readAsBytes instead of readAsBytesSync :

var bytes = await widget.image.readAsBytes();
var base64img = base64Encode(bytes);
JS1
  • 631
  • 2
  • 7
  • 23
0

Try using this method

import 'dart:convert';
import 'dart:io';

import 'package:image/image.dart';

String imageToBase64(File file, {int? height}) {
  final image = decodeImage(file.readAsBytesSync())!;
  final resizedImage = copyResize(image, height: height ?? 800);
  return base64Encode(encodeJpg(resizedImage));
}
Baha
  • 1
  • 2
  • for installing - package:image `flutter pub add image` – Baha Mar 09 '22 at 18:56
  • Tried it, I got this error : "The following NoSuchMethodError was thrown while handling a gesture: 'readAsBytesSync' Dynamic call of null. Receiver: Instance of 'XFile' Arguments: []" – JS1 Mar 09 '22 at 19:09
  • In this case, you need to convert to the required type, here is an example https://stackoverflow.com/a/68081428/8155939 – Baha Mar 09 '22 at 20:36
  • Same error, converting the path to a File is what I already tried to do. – JS1 Mar 10 '22 at 11:09