tryReadImageFromPath method
Try to find and read an image file, falling back to clipboard search.
Implementation
Future<({String path, ImageWithDimensions image})?> tryReadImageFromPath(
String text,
) async {
final cleanedPath = asImageFilePath(text);
if (cleanedPath == null) return null;
Uint8List? imageBuffer;
try {
if (cleanedPath.startsWith('/')) {
imageBuffer = await File(cleanedPath).readAsBytes();
} else {
final clipboardPath = await getImagePathFromClipboard();
if (clipboardPath != null &&
cleanedPath == clipboardPath.split('/').last) {
imageBuffer = await File(clipboardPath).readAsBytes();
}
}
} catch (e) {
_logError(e);
return null;
}
if (imageBuffer == null || imageBuffer.isEmpty) return null;
final ext = cleanedPath.split('.').last.toLowerCase();
final buffer = Uint8List.fromList(imageBuffer);
final resized = await maybeResizeAndDownsampleImageBuffer(
buffer,
buffer.length,
ext.isEmpty ? 'png' : ext,
);
final base64Image = base64Encode(resized.buffer);
final mediaType = detectImageFormatFromBase64(base64Image);
return (
path: cleanedPath,
image: ImageWithDimensions(
base64: base64Image,
mediaType: mediaType.value,
dimensions: resized.dimensions,
),
);
}