detectImageFormat function
Detects image format from asset path or image data.
Returns the format string ('png', 'svg', 'jpg', 'jpeg', etc.) based on:
- File extension from
assetPathif provided - Image data magic bytes if
imageDatais provided - Returns null if format cannot be determined
Implementation
String? detectImageFormat(String? assetPath, Uint8List? imageData) {
// First, try to detect from file extension
if (assetPath != null && assetPath.isNotEmpty) {
final extension = assetPath.split('.').last.toLowerCase();
if (extension == 'svg') return 'svg';
if (extension == 'png') return 'png';
if (extension == 'jpg' || extension == 'jpeg') return 'jpg';
if (extension == 'gif') return 'gif';
if (extension == 'webp') return 'webp';
}
// If no extension or format not detected, try to detect from image data magic bytes
if (imageData != null && imageData.length >= 4) {
// PNG: 89 50 4E 47 (PNG signature)
if (imageData[0] == 0x89 &&
imageData[1] == 0x50 &&
imageData[2] == 0x4E &&
imageData[3] == 0x47) {
return 'png';
}
// JPEG: FF D8 FF
if (imageData[0] == 0xFF &&
imageData[1] == 0xD8 &&
imageData[2] == 0xFF) {
return 'jpg';
}
// GIF: 47 49 46 38 (GIF8)
if (imageData[0] == 0x47 &&
imageData[1] == 0x49 &&
imageData[2] == 0x46 &&
imageData[3] == 0x38) {
return 'gif';
}
// SVG: Check if it starts with '<' or contains 'svg' in the first bytes
// SVG files are XML, so they typically start with '<' or whitespace followed by '<'
final firstBytes = String.fromCharCodes(imageData.take(100));
if (firstBytes.trim().startsWith('<') &&
(firstBytes.contains('<svg') || firstBytes.contains('SVG'))) {
return 'svg';
}
}
// Default to PNG if we have image data but can't determine format
// (PNG is the most common format for icons)
if (imageData != null) {
return 'png';
}
return null;
}