import 'dart:convert'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:file_picker/file_picker.dart'; /// Picks a photo from the device and returns it as a small PNG data URI, /// ready to store as a profile `pic`. Null when nothing was picked or the /// file was not an image. class PhotoPicker { /// Long edge of the stored portrait. Big enough for the largest avatar on /// a 3x screen, small enough to keep in local storage. static const int _edge = 256; static Future pickPortrait() async { final FilePickerResult? result = await FilePicker.pickFiles(type: FileType.image, withData: true); final Uint8List? bytes = result == null || result.files.isEmpty ? null : result.files.first.bytes; if (bytes == null) { return null; } try { final ui.Codec codec = await ui.instantiateImageCodec(bytes, targetWidth: _edge, targetHeight: null); final ui.FrameInfo frame = await codec.getNextFrame(); final ByteData? png = await frame.image.toByteData(format: ui.ImageByteFormat.png); if (png == null) { return null; } return "data:image/png;base64,${base64Encode(png.buffer.asUint8List())}"; } catch (e) { return null; } } }