'Convert image file into base64 image in Flutter Web
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.
Solution 1:[1]
Found the solution, using readAsBytes instead of readAsBytesSync :
var bytes = await widget.image.readAsBytes();
var base64img = base64Encode(bytes);
Solution 2:[2]
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));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JS1 |
| Solution 2 | Baha |
