detectImageFormat static method

Future<String?> detectImageFormat(
  1. String filePath
)

Implementation

static Future<String?> detectImageFormat(String filePath) async {
  // 在 Web 平台上,不支持本地文件访问
  if (kIsWeb) {
    return null;
  }

  final file = File(filePath);
  final List<int> bytes;
  try {
    bytes = await file.openRead(0, 20).first;
  } catch (_) {
    // 文件不存在、空文件或读取失败,均视为无法识别格式
    return null;
  }

  if (bytes.length < 4) return null;

  if (bytes.length >= 8 &&
      bytes.sublist(0, 8).equals([
        0x89,
        0x50,
        0x4E,
        0x47,
        0x0D,
        0x0A,
        0x1A,
        0x0A,
      ])) {
    return 'png';
  }

  if (bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) {
    return 'jpeg';
  }

  if ((bytes[0] == 0x47 &&
      bytes[1] == 0x49 &&
      bytes[2] == 0x46 &&
      bytes[3] == 0x38)) {
    return 'gif';
  }

  if (bytes[0] == 0x42 && bytes[1] == 0x4D) {
    return 'bmp';
  }

  if ((bytes[0] == 0x49 &&
          bytes[1] == 0x49 &&
          bytes[2] == 0x2A &&
          bytes[3] == 0x00) ||
      (bytes[0] == 0x4D &&
          bytes[1] == 0x4D &&
          bytes[2] == 0x00 &&
          bytes[3] == 0x2A)) {
    return 'tiff';
  }

  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 'webp';
  }

  if (bytes[0] == 0x00 &&
      bytes[1] == 0x00 &&
      bytes[2] == 0x01 &&
      bytes[3] == 0x00) {
    return 'ico';
  }

  if (bytes.length >= 12 &&
      bytes.sublist(4, 12).equals([
        0x66,
        0x74,
        0x79,
        0x70,
        0x68,
        0x65,
        0x69,
        0x63,
      ])) {
    return 'heic'; // or heif
  }

  return null;
}