image_utils.dart
1 import 'dart:io'; 2 import 'dart:ui' as ui; 3 4 import 'package:path_provider/path_provider.dart'; 5 6 /// Resize an image file to fit within [maxWidth] x [maxHeight], 7 /// maintaining aspect ratio. Saves as PNG to a temporary file. 8 /// Used on macOS where ImagePicker's maxWidth/maxHeight are unavailable. 9 Future<String> resizeImageToFile( 10 String sourcePath, { 11 required int maxWidth, 12 required int maxHeight, 13 }) async { 14 final bytes = await File(sourcePath).readAsBytes(); 15 final codec = await ui.instantiateImageCodec( 16 bytes, 17 targetWidth: maxWidth, 18 targetHeight: maxHeight, 19 ); 20 final frame = await codec.getNextFrame(); 21 final byteData = await frame.image.toByteData( 22 format: ui.ImageByteFormat.png, 23 ); 24 frame.image.dispose(); 25 26 final dir = await getTemporaryDirectory(); 27 final timestamp = DateTime.now().millisecondsSinceEpoch; 28 final resizedPath = '${dir.path}/resized_$timestamp.png'; 29 await File(resizedPath).writeAsBytes( 30 byteData!.buffer.asUint8List(), 31 ); 32 return resizedPath; 33 }