Open In App

How to Create Image Cropper App in Flutter?

Last Updated : 19 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is a robust framework that allows developers to create beautiful and responsive mobile applications. Images are an essential part of any mobile application, and developers need to be able to manipulate them effectively. Image cropping is a common task when working with images, and the image_cropper package is an excellent tool for achieving this. This package has features like cropping, zooming, and rotating a picture. In this article, we will walk you through the process of selecting and cropping an image using the image_cropper and image_picker packages in Flutter. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

To get started with building an image cropping app in Flutter, we need to create a new Flutter project. Here are the steps to create a new Flutter project using the Flutter CLI:

Step 1: Open a terminal window and navigate to the directory where you want to create the project.

Step 2: Run the following command to create a new Flutter project:

flutter create my_image_cropper

Step 3: Wait for the project creation process to complete. This will generate a new Flutter project in the directory ‘my_image_cropper’.

Install the package

Step 1: Open your Flutter project in an IDE or code editor of your choice.

Step 2: Add image_cropper and image_picker to your pubspec.yaml file, as a dependency. You can do this by adding the following line under the dependencies section:

dependencies:
  image_cropper: ^3.0.1
  image_picker: ^0.8.6+1

Make sure to replace the above versions with the latest version available.

OR

Open a terminal window and navigate to the root directory of your Flutter project. Run the following command to add the above packages as a dependency in your project:

flutter pub add image_cropper
flutter pub add image_picker

Step 3: Save the changes to your pubspec.yaml file.

Step 4: Run flutter pub get in your terminal or IDE’s command line interface to download and install the image_cropper and image_picker packages and their dependencies.

Step 5: Import the packages in your Dart code by adding the following line at the beginning of your file:

import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

Now you can use the classes and functions provided by the image_cropper and image_picker packages in your code. Note that you might need to run flutter clean and rebuild your app after adding new packages to your pubspec.yaml file, to make sure that the new packages are correctly linked to your project.

Select the Image

The first step in using the image_cropper package is to select an image with the help of the image_picker package. You can do this using the ImagePicker instance provided by the image_picker package where you can pick or select an image from the gallery or camera of your choice. It returns the loaded image in XFile format.  To execute this, we use the _pickImage() function. Here’s an example of how to pick and display an image in Flutter:

Dart




import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
  
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);
  
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}
  
class _HomeScreenState extends State<HomeScreen> {
  File? imageFile;
    
  Future _pickImage() async {
    final pickedImage =
        await ImagePicker().pickImage(source: ImageSource.gallery);
  
    if (pickedImage != null) {
      setState(() {
        imageFile = File(pickedImage.path);
      });
    }
  }
    
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Image Editor'),
      ),
      body: Column(
          children: [
            Expanded(
                flex: 3,
                child: imageFile != null
                    ? Container(
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        child: Image.file(imageFile!))
                    : const Center(
                        child: Text("Add a picture"),
                      )),
            Expanded(
                child: Center(
              child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            color: Colors.black, borderRadius: BorderRadius.circular(10)),
        child: IconButton(
          onPressed: _pickImage,
          icon: Icon(Icons.add),
          color: Colors.white,
                ))
            ))
          ],
        ),
    );
  }
}


In this example, we create an ImagePicker instance to call the pickImage function to load an image from the gallery. We can also pick an image from instant capture by changing the source to the ImageSource.camera instead of the ImageSource.gallery. Once the image is picked, we convert the XFile format to File format. We then use setState to update the imageFile variable with the picked image data. We display this picked image using the Image.file widget. On clicking the add icon button, the image picker will be launched to pick an image from the gallery.

Crop the Image

Now that we have picked an image with the help of the image_picker package, let’s see how we can use the image_cropper package to crop the image to a specific size or aspect ratio, and rotate and zoom it as well. To do this, we use the _cropImage() function to execute the cropping features. Here’s an example of the function that we will use for implementing the features:

Dart




import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
  
// Add the below function inside your working class
Future _cropImage() async {
    if (imageFile != null) {
      CroppedFile? cropped = await ImageCropper().cropImage(
          sourcePath: imageFile!.path,
          aspectRatioPresets: 
               [
                  CropAspectRatioPreset.square,
                  CropAspectRatioPreset.ratio3x2,
                  CropAspectRatioPreset.original,
                  CropAspectRatioPreset.ratio4x3,
                  CropAspectRatioPreset.ratio16x9
                ]
               
          uiSettings: [
            AndroidUiSettings(
                toolbarTitle: 'Crop',
                cropGridColor: Colors.black,
                initAspectRatio: CropAspectRatioPreset.original,
                lockAspectRatio: false),
            IOSUiSettings(title: 'Crop')
          ]);
  
      if (cropped != null) {
        setState(() {
          imageFile = File(cropped.path);
        });
      }
    }
  }


In this example, we’re using the _cropImage function to execute the cropping features. When this function is executed, it will launch the editor named ‘Crop’ (or any other name you choose) where you can execute the features such as cropping, rotating, and zooming the picture.

For using it, we create an ImageCropper instance and call the cropImage function with the sourcePath, aspectRatioPresets, and uiSettings parameters. The cropImage function will crop the image to the specified size as we have defined in our aspectRatioPresets, and rotate and zoom the picture. You can edit the dialog box by editing the uiSettings parameter and can also make changes with regard to the specific platform it is being used in (such as Android and IOS). It returns a CroppedFile containing the cropped image data. We then use setState to update the imageFile variable with the converted cropped image data to File format and display the cropped image using the Image.file widget. Note that there are more parameters that you can explore. Read image_cropper’s official documentation for more information.

Clear the Image

After picking and cropping, we need to clear the picked image data as well to work with the next picked image data. We use the _clearImage() function for this. Here’s an example of the function:

Dart




import 'dart:io';
  
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
  
// Add the below function to your working class
void _clearImage() {
    setState(() {
      imageFile = null;
    });
  }


In this example, we use setState to update the imageFile to null. 

Full working code

Now that we are done with the functions, let us integrate those functions into our app. Here’s the full working code for it:

Dart




import 'dart:io';
  
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
  
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);
  
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}
  
class _HomeScreenState extends State<HomeScreen> {
  File? imageFile;
  
  Future _pickImage() async {
    final pickedImage =
        await ImagePicker().pickImage(source: ImageSource.gallery);
  
    if (pickedImage != null) {
      setState(() {
        imageFile = File(pickedImage.path);
      });
    }
  }
  
  Future _cropImage() async {
    if (imageFile != null) {
      CroppedFile? cropped = await ImageCropper().cropImage(
          sourcePath: imageFile!.path,
          aspectRatioPresets: 
               [
                  CropAspectRatioPreset.square,
                  CropAspectRatioPreset.ratio3x2,
                  CropAspectRatioPreset.original,
                  CropAspectRatioPreset.ratio4x3,
                  CropAspectRatioPreset.ratio16x9
                ]
               
          uiSettings: [
            AndroidUiSettings(
                toolbarTitle: 'Crop',
                cropGridColor: Colors.black,
                initAspectRatio: CropAspectRatioPreset.original,
                lockAspectRatio: false),
            IOSUiSettings(title: 'Crop')
          ]);
  
      if (cropped != null) {
        setState(() {
          imageFile = File(cropped.path);
        });
      }
    }
  }
  
  void _clearImage() {
    setState(() {
      imageFile = null;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.black,
            title: const Text("Crop Your Image")),
        body: Column(
          children: [
            Expanded(
                flex: 3,
                child: imageFile != null
                    ? Container(
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        child: Image.file(imageFile!))
                    : const Center(
                        child: Text("Add a picture"),
                      )),
            Expanded(
                child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildIconButton(icon: Icons.add, onpressed: _pickImage),
                  _buildIconButton(icon: Icons.crop, onpressed: _cropImage),
                  _buildIconButton(icon: Icons.clear, onpressed: _clearImage),
                ],
              ),
            ))
          ],
        ));
  }
  
  Widget _buildIconButton(
      {required IconData icon, required void Function()? onpressed}) {
    return Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            color: Colors.black, borderRadius: BorderRadius.circular(10)),
        child: IconButton(
          onPressed: onpressed,
          icon: Icon(icon),
          color: Colors.white,
        ));
  }
}


Output:

Conclusion

In this article, we’ve explored how we can create our own image-cropping app using the image_picker package for selecting an image and the image_cropper package to implement features like crop, rotate and zoom. The image_cropper package provides a powerful and flexible set of tools for working with images and can help you create more engaging and visually appealing apps.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads