import 'dart:io'; import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; /// Service pour gérer l'accès aux images et vidéos class ImageService { final ImagePicker _picker = ImagePicker(); /// Sélectionner une image depuis la galerie Future pickImageFromGallery() async { try { final XFile? image = await _picker.pickImage( source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 90, ); return image != null ? File(image.path) : null; } on PlatformException catch (e) { throw ImagePickerException('Failed to pick image: ${e.message}'); } } /// Capturer une image avec la caméra Future captureImageFromCamera() async { try { final XFile? photo = await _picker.pickImage( source: ImageSource.camera, maxWidth: 1920, maxHeight: 1920, imageQuality: 90, ); return photo != null ? File(photo.path) : null; } on PlatformException catch (e) { throw ImagePickerException('Failed to capture image: ${e.message}'); } } /// Sélectionner une vidéo depuis la galerie Future pickVideoFromGallery() async { try { final XFile? video = await _picker.pickVideo( source: ImageSource.gallery, maxDuration: const Duration(minutes: 2), ); return video != null ? File(video.path) : null; } on PlatformException catch (e) { throw ImagePickerException('Failed to pick video: ${e.message}'); } } /// Capturer une vidéo avec la caméra Future captureVideoFromCamera() async { try { final XFile? video = await _picker.pickVideo( source: ImageSource.camera, maxDuration: const Duration(minutes: 2), ); return video != null ? File(video.path) : null; } on PlatformException catch (e) { throw ImagePickerException('Failed to capture video: ${e.message}'); } } /// Sauvegarder un fichier dans le dossier documents Future saveToAppDirectory(File sourceFile, String fileName) async { try { final directory = await getApplicationDocumentsDirectory(); final filePath = path.join(directory.path, fileName); return await sourceFile.copy(filePath); } catch (e) { throw ImagePickerException('Failed to save file: $e'); } } /// Obtenir la taille d'un fichier en MB double getFileSizeInMB(File file) { return file.lengthSync() / (1024 * 1024); } } /// Exception personnalisée pour ImageService class ImagePickerException implements Exception { final String message; ImagePickerException(this.message); @override String toString() => 'ImagePickerException: $message'; }