Preview:
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

import 'app_style.dart';

class ImagePickerHelper {
  static Future<void> pickImage({
    required Function(File? file) onDone,
  }) async {
    final pickedImage =
        await ImagePicker.platform.pickImage(source: ImageSource.gallery);

    if (pickedImage == null) {
      onDone.call(null);
      return;
    }

    final pickedFile = File(pickedImage.path);
    final croppedImage = await _cropImage(pickedFile);
    final compressedImage = await _compressFile(croppedImage);
    if (compressedImage == null) {
      onDone.call(null);
      return;
    }


    onDone.call(compressedImage);
  }

  static String getFileSize(File file) {
    final fileSizeInMB =
    (file.lengthSync() / (1024 * 1024)).toStringAsFixed(2);
    return fileSizeInMB;
  }

  static Future<File?>? _cropImage(File file) async {
    final croppedFile = await ImageCropper.platform.cropImage(
      sourcePath: file.path,
      aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
      compressQuality: 60,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: 'Crop Image',
          toolbarColor: AppStyle.lightPurple,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.square,
          lockAspectRatio: true,
        ),
        IOSUiSettings(
          minimumAspectRatio: 1.0,
          aspectRatioLockEnabled: true,
          resetAspectRatioEnabled: true,
        ),
      ],
    );

    if (croppedFile == null) return null;
    return File(croppedFile.path);
  }

  static Future<File?> _compressFile(File? file) async {
    if (file == null) return null;

    final targetPath =
        '${file.parent.path}/compressed_${file.path.split('/').last}';

    final XFile? result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      quality: 60,
      keepExif: false,
    );

    if (result == null) return null;
    return File(result.path);
  }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter