getImageFromPhone static method

Future<MemoryImage?> getImageFromPhone({
  1. bool camera = false,
})

Retrieves an image from the device's camera or gallery, optionally cropping it, and returns a MemoryImage.

The method utilizes the image_picker and image_cropper plugins to enable image selection and cropping.

To use this method, you must have implemented the image_picker and image_cropper plugins. Add the following dependencies to your pubspec.yaml file:

dependencies:
  image_picker: ^latest_version
  image_cropper: ^latest_version

Example usage:

MemoryImage? memoryImage = await getImageFromPhone(camera: true);
if (memoryImage != null) {
  // Use the memoryImage in a Flutter widget.
}

The optional parameter camera determines whether the image is taken from the camera (true) or gallery (false).

Returns a MemoryImage of the selected and optionally cropped image, or null if no image was selected.

Implementation

static Future<MemoryImage?> getImageFromPhone({bool camera = false}) async {
  final ImagePicker picker = ImagePicker();
  XFile? image = await picker.pickImage(
    source: camera ? ImageSource.camera : ImageSource.gallery,
  );
  if (image != null) {
    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: image.path,
      aspectRatioPresets: [
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9,
      ],
    );
    if (croppedFile != null) {
      image = XFile(croppedFile.path);
    }
    return MemoryImage(await image.readAsBytes());
  }
  return null;
}