How to Crop Images Centered in Flutter - Simple Guide

Add the necessary import statements for the image package:

import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';

Create a function to crop and save the centered image:

Future<void> cropAndSaveCenteredImage(String imagePath, double cropWidth, double cropHeight, String fileName) async {
  // Read the image from the file path
  File imageFile = File(imagePath);
  List<int> imageBytes = await imageFile.readAsBytes();
  img.Image image = img.decodeImage(imageBytes);

  // Calculate the center position for cropping
  int centerX = image.width ~/ 2;
  int centerY = image.height ~/ 2;

  // Calculate the crop rectangle based on the center position
  int cropX = (centerX - cropWidth ~/ 2).clamp(0, image.width);
  int cropY = (centerY - cropHeight ~/ 2).clamp(0, image.height);

  // Crop the image
  img.Image croppedImage = img.copyCrop(image, cropX, cropY, cropWidth.toInt(), cropHeight.toInt());

  // Get the document directory to save the image
  Directory directory = await getApplicationDocumentsDirectory();
  String filePath = '${directory.path}/$fileName.png';

  // Save the image to file
  File file = File(filePath);
  await file.writeAsBytes(img.encodePng(croppedImage));

  // Display the file path
  print('Image saved to: $filePath');

Call the function with the image file path, crop width, crop height, and the desired filename:

void main() async {
  // Replace 'image_path.png' with the actual path of your image file
  String imagePath = 'image_path.png';

  // Define the desired crop width and height
  double cropWidth = 200.0;
  double cropHeight = 200.0;

  // Define the desired filename (without the extension)
  String fileName = 'cropped_image';

  // Crop and save the centered image with the specified filename
  await cropAndSaveCenteredImage(imagePath, cropWidth, cropHeight, fileName);

Make sure to replace 'image_path.png' with the actual path to your image file. The code will read the image, calculate the center position, create a crop rectangle around it, and then crop the image using the image package. The cropped image will be saved as a new PNG image file with the custom filename in the application's document directory. The file path will be printed in the console for your reference.

Again, remember to use appropriate error handling and check for null values when working with files and images.