mediaTypeFromBytes function
Detect image media type from magic bytes.
Implementation
String? mediaTypeFromBytes(List<int> bytes) {
if (bytes.length < 4) return null;
// JPEG: FF D8 FF
if (bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) {
return 'image/jpeg';
}
// PNG: 89 50 4E 47
if (bytes[0] == 0x89 &&
bytes[1] == 0x50 &&
bytes[2] == 0x4E &&
bytes[3] == 0x47) {
return 'image/png';
}
// GIF: 47 49 46 38
if (bytes[0] == 0x47 &&
bytes[1] == 0x49 &&
bytes[2] == 0x46 &&
bytes[3] == 0x38) {
return 'image/gif';
}
// WebP: 52 49 46 46 ... 57 45 42 50
if (bytes.length >= 12 &&
bytes[0] == 0x52 &&
bytes[1] == 0x49 &&
bytes[2] == 0x46 &&
bytes[3] == 0x46 &&
bytes[8] == 0x57 &&
bytes[9] == 0x45 &&
bytes[10] == 0x42 &&
bytes[11] == 0x50) {
return 'image/webp';
}
// PDF: 25 50 44 46 (%PDF)
if (bytes[0] == 0x25 &&
bytes[1] == 0x50 &&
bytes[2] == 0x44 &&
bytes[3] == 0x46) {
return 'application/pdf';
}
return null;
}