fixExifRotation static method

Future<File> fixExifRotation(
  1. String imagePath
)

Fix EXIF rotation issue basato sulla soluzione di Dominik Roszkowski https://roszkowski.dev/how-to-fix-rotated-image-from-camera-in-flutter/

Implementation

static Future<File> fixExifRotation(String imagePath) async {
  final originalFile = File(imagePath);
  List<int> imageBytes = await originalFile.readAsBytes();

  final originalImage = img.decodeImage(Uint8List.fromList(imageBytes));
  if (originalImage == null) {
    debugPrint('Impossibile decodificare immagine per fix EXIF');
    return originalFile;
  }

  final height = originalImage.height;
  final width = originalImage.width;

  // Se l'immagine è già in portrait, probabilmente non serve rotazione
  if (height >= width) {
    return originalFile;
  }

  // Leggi i dati EXIF per controllare l'orientamento
  Map<String, IfdTag>? exifData;
  try {
    exifData = await readExifFromBytes(Uint8List.fromList(imageBytes));
  } catch (e) {
    debugPrint('Impossibile leggere dati EXIF: $e');
    // Se non ci sono dati EXIF, ritorna l'immagine originale
    return originalFile;
  }

  img.Image fixedImage = originalImage;

  if (height < width) {
    debugPrint('Rotazione immagine necessaria basata su EXIF');

    final orientationTag = exifData['Image Orientation'];
    if (orientationTag != null) {
      final orientation = orientationTag.printable;

      if (orientation.contains('Horizontal')) {
        fixedImage = img.copyRotate(originalImage, angle: 90);
      } else if (orientation.contains('180')) {
        fixedImage = img.copyRotate(originalImage, angle: -90);
      } else if (orientation.contains('90')) {
        fixedImage = img.copyRotate(originalImage, angle: 90);
      } else if (orientation.contains('270')) {
        fixedImage = img.copyRotate(originalImage, angle: -90);
      } else {
        // Nessuna rotazione necessaria
        fixedImage = originalImage;
      }
    }
  }

  // Salva l'immagine corretta in JPG con qualità 95%
  final fixedFile =
      await originalFile.writeAsBytes(img.encodeJpg(fixedImage, quality: 95));

  return fixedFile;
}