Image picker helper

PHOTO EMBED

Wed Jan 08 2025 05:57:20 GMT+0000 (Coordinated Universal Time)

Saved by @Samuel1347 #dart

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);
  }
}
content_copyCOPY

The ImagePickerHelper class is a utility for working with images in the Flutter application. It provides methods for selecting, cropping, compressing, and resizing images. The main purpose of the class is to simplify the processing of images before uploading or using them in an application.