encodeImageToDataUrl static method
- String filePath
Encodes an image file to a Base64 data URL. @param filePath The path to the image file. @return A Future that resolves to a Base64 data URL string.
Implementation
static Future<String> encodeImageToDataUrl(String filePath) async {
// Read the image file as bytes
final bytes = File(filePath).readAsBytesSync();
// Encode the image to Base64
final encodedImage = base64Encode(bytes);
// Extract the file extension
final fileExtension = filePath.split('.').last.toLowerCase();
// Define MIME types
final mimeTypes = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'webp': 'image/webp',
};
// Determine the MIME type
final mimeType = mimeTypes[fileExtension] ?? 'image/png';
// Return the formatted data URL
return "data:$mimeType;base64,$encodedImage";
}