Home

Awesome

Image Cropper

pub package

A Flutter plugin for Android, iOS and Web supports cropping images. This plugin is based on three different native libraries so it comes with different UI between these platforms.

Introduction

Image Cropper doesn't manipulate images in Dart codes directly, instead, the plugin uses Platform Channel to expose Dart APIs that Flutter application can use to communicate with three very powerful native libraries (uCrop, TOCropViewController and Cropper.js) to crop and rotate images. Because of that, all credits belong to these libraries.

uCrop - Yalantis

GitHub watchers GitHub stars GitHub forks License

This project aims to provide an ultimate and flexible image cropping experience. Made in Yalantis

<p align="center"> <img src="https://github.com/hnvn/flutter_image_cropper/blob/master/image_cropper/screenshots/cropper_android.gif?raw=true" width="200" /> </p>

TOCropViewController - Tim Oliver

GitHub watchers GitHub stars GitHub forks Version GitHub license

TOCropViewController is an open-source UIViewController subclass to crop out sections of UIImage objects, as well as perform basic rotations. It is excellent for things like editing profile pictures, or sharing parts of a photo online. It has been designed with the iOS Photos app editor in mind, and as such, behaves in a way that should already feel familiar to users of iOS.

<p align="center"> <img src="https://github.com/hnvn/flutter_image_cropper/blob/master/image_cropper/screenshots/cropper_ios.gif?raw=true" width="200" /> </p>

Cropper.js - Fengyuan Chen

GitHub watchers GitHub stars GitHub forks npm version GitHub license

JavaScript image cropper.

<p align="center"> <img src="https://github.com/hnvn/flutter_image_cropper/blob/master/image_cropper/screenshots/cropper_web.png?raw=true" width="400"/> </p>

How to install

Android

<activity
    android:name="com.yalantis.ucrop.UCropActivity"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

Note:

From v1.2.0, you need to migrate your android project to v2 embedding (detail)

iOS

Web

<head>
  ....

  <!-- cropperjs -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>

  ....
</head>

Usage

Required parameters

Optional parameters

Note

Customization

Android

<details> <summary>Click to view detail</summary> <br/>

Image Cropper provides a helper class called AndroidUiSettings that wraps all properties can be used to customize UI in uCrop library.

PropertyDescriptionType
toolbarTitledesired text for Toolbar titleString
toolbarColordesired color of the ToolbarColor
statusBarColordesired color of statusColor
toolbarWidgetColordesired color of Toolbar text and buttons (default is darker orange)Color
backgroundColordesired background color that should be applied to the root viewColor
activeControlsWidgetColordesired resolved color of the active and selected widget and progress wheel middle line (default is white)Color
dimmedLayerColordesired color of dimmed area around the crop boundsColor
cropFrameColordesired color of crop frameColor
cropGridColordesired color of crop grid/guidelinesColor
cropFrameStrokeWidthdesired width of crop frame line in pixelsint
cropGridRowCountcrop grid rows countint
cropGridColumnCountcrop grid columns countint
cropGridStrokeWidthdesired width of crop grid lines in pixelsint
showCropGridset to true if you want to see a crop grid/guidelines on top of an imagebool
lockAspectRatioset to true if you want to lock the aspect ratio of crop bounds with a fixed value (locked by default)bool
hideBottomControlsset to true to hide the bottom controls (shown by default)bool
initAspectRatiodesired aspect ratio is applied (from the list of given aspect ratio presets) when starting the cropperCropAspectRatioPreset
cropStylecontrols the style of crop bounds, it can be rectangle or circle style (default is CropStyle.rectangle).CropStyle
aspectRatioPresetscontrols the list of aspect ratios in the crop menu view.List<CropAspectRatioPresetData>
</details>

iOS

<details> <summary>Click to view detail</summary> <br/>

Image Cropper provides a helper class called IOUiSettings that wraps all properties can be used to customize UI in TOCropViewController library.

PropertyDescriptionType
minimumAspectRatioThe minimum croping aspect ratio. If set, user is prevented from setting cropping rectangle to lower aspect ratio than defined by the parameterdouble
rectXThe initial rect of cropping: x.double
rectYThe initial rect of cropping: y.double
rectWidthThe initial rect of cropping: width.double
rectHeightThe initial rect of cropping: height.double
showActivitySheetOnDoneIf true, when the user hits 'Done', a UIActivityController will appear before the view controller endsbool
showCancelConfirmationDialogShows a confirmation dialog when the user hits 'Cancel' and there are pending changes (default is false)bool
rotateClockwiseButtonHiddenWhen disabled, an additional rotation button that rotates the canvas in 90-degree segments in a clockwise direction is shown in the toolbar (default is false)bool
embedInNavigationControllerEmbed the presented TOCropViewController in a UINavigationController. (default is false)bool
hidesNavigationBarIf this controller is embedded in UINavigationController its navigation bar is hidden by default. Set this property to false to show the navigation bar. This must be set before this controller is presentedbool
rotateButtonsHiddenWhen enabled, hides the rotation button, as well as the alternative rotation button visible when showClockwiseRotationButton is set to YES (default is false)bool
resetButtonHiddenWhen enabled, hides the 'Reset' button on the toolbar (default is false)bool
aspectRatioPickerButtonHiddenWhen enabled, hides the 'Aspect Ratio Picker' button on the toolbar (default is false)bool
resetAspectRatioEnabledIf true, tapping the reset button will also reset the aspect ratio back to the image default ratio. Otherwise, the reset will just zoom out to the current aspect ratio. If this is set to false, and aspectRatioLockEnabled is set to true, then the aspect ratio button will automatically be hidden from the toolbar (default is true)bool
aspectRatioLockDimensionSwapEnabledIf true, a custom aspect ratio is set, and the aspectRatioLockEnabled is set to true, the crop box will swap it's dimensions depending on portrait or landscape sized images. This value also controls whether the dimensions can swap when the image is rotated (default is false)bool
aspectRatioLockEnabledIf true, while it can still be resized, the crop box will be locked to its current aspect ratio. If this is set to true, and resetAspectRatioEnabled is set to false, then the aspect ratio button will automatically be hidden from the toolbar (default is false)bool
titleTitle text that appears at the top of the view controller.String
doneButtonTitleTitle for the 'Done' button. Setting this will override the Default which is a localized string for "Done"String
cancelButtonTitleTitle for the 'Cancel' button. Setting this will override the Default which is a localized string for "Cancel"String
cropStylecontrols the style of crop bounds, it can be rectangle or circle style (default is CropStyle.rectangle).CropStyle
aspectRatioPresetscontrols the list of aspect ratios in the crop menu view.List<CropAspectRatioPresetData>
</details>

Web

<details> <summary>Click to view detail</summary> <br/>

Image Cropper provides a helper class called WebUiSettings that wraps all properties can be used to customize UI in cropperjs library.

PropertyDescriptionType
sizeDisplay size of the cropper. Default = { width: 500, height: 500 }CropperSize
viewwModeDefine the view mode of the cropper. Details of available options in View Mode. Default = 0WebViewMode
dragModeDefine the dragging mode of the cropper. Details of available options in Drag Mode. Default = cropWebDragMode
initialAspectRatioDefine the initial aspect ratio of the crop box. By default, it is the same as the aspect ratio of the canvas (image wrapper). Note: Only available when the aspectRatio option is set to NaN.num
checkCrossOriginCheck if the current image is a cross-origin. Default = true image.bool
checkOrientationCheck the current image's Exif Orientation information. Note that only a JPEG image may contain Exif Orientation information. Requires to set both the rotatable and scalable options to true at the same time. Default = truebool
modalShow the black modal above the image and under the crop box. Default = truebool
guidesShow the dashed lines above the crop box. Default = truebool
centerShow the center indicator above the crop box. Default = truebool
highlightShow the white modal above the crop box (highlight the crop box). Default = truebool
backgroundShow the grid background of the container. Default = truebool
movableEnable to move the image. Default = truebool
rotatableEnable to rotate the image. Default = truebool
scalableEnable to scale the image. Default = truebool
zoomableEnable to zoom the image. Default = truebool
zoomOnTouchEnable to zoom the image by dragging touch. Default = truebool
zoomOnWheelEnable to zoom the image by mouse wheeling. Default = truebool
wheelZoomRatioDefine zoom ratio when zooming the image by mouse wheeling. Default = 0.1num
cropBoxMovableEnable to move the crop box by dragging. Default = truebool
cropBoxResizableEnable to resize the crop box by dragging. Default = truebool
toggleDragModeOnDblclickEnable to toggle drag mode between "crop" and "move" when clicking twice on the cropper. Default = truebool
minContainerWidthThe minimum width of the container. Default = 200num
minContainerHeightThe minimum height of the container. Default = 100num
minCropBoxWidthThe minimum width of the crop box. Default = 0num
minCropBoxHeightThe minimum height of the crop box. Default = 0num
presentStylePresentation style of cropper, either a dialog or a page (route). Default = dialogWebPresentStyle
contextCurrent BuildContext. The context is required to show cropper dialog or routeBuildContext
customDialogBuilderBuilder to customize the cropper DialogWebDialogBuilder
customRouteBuilderBuilder to customize the cropper PageRouteWebRouteBuilder
barrierColorBarrier color for displayed DialogColor
translationsTranslations to displayWebTranslations
themeDataControl UI customizationWebThemeData

View Mode:

If you set viewMode to 0, the crop box can extend outside the canvas, while a value of 1, 2, or 3 will restrict the crop box to the size of the canvas. viewMode of 2 or 3 will additionally restrict the canvas to the container. There is no difference between 2 and 3 when the proportions of the canvas and the container are the same.

Drag Mode:

Note:

If using WebDialogBuilder and WebRouteBuilder to customize cropper dialog and route, the customization codes must to call following functions:


  class CropperDialog extends StatefulWidget {
    ...
  }  

  class _CropperDialogState extends State<CropperDialog> {
    @override
    void initState() {
      super.initState();
      /// IMPORTANT: must to call this function
      widget.initCropper();
    }

    @override
    Widget build(BuildContext context) {
      Dialog(
        child: Column(
          children: [
            ...
            cropper,
            ...
            TextButton(
              onPressed: () async {
                /// IMPORTANT: to call crop() function and return
                /// result data to plugin, for example:
                final result = await crop();
                Navigator.of(context).pop(result);
              },
              child: Text('Crop'),
            )
          ]
        ),
      );
    }
  }

  WebUiSettings(
    ...
    customDialogBuilder: (cropper, initCropper, crop, rotate, scale) {
      return CropperDialog(
        cropper: cropper,
        initCropper: initCropper,
        crop: crop,
        rotate: rotate,
        scale: scale,
      );
    },
    ...
  )

</details>

Example


import 'package:image_cropper/image_cropper.dart';

CroppedFile croppedFile = await ImageCropper().cropImage(
    sourcePath: imageFile.path,
    uiSettings: [
      AndroidUiSettings(
        toolbarTitle: 'Cropper',
        toolbarColor: Colors.deepOrange,
        toolbarWidgetColor: Colors.white,
        aspectRatioPresets: [
          CropAspectRatioPreset.original,
          CropAspectRatioPreset.square,
          CropAspectRatioPresetCustom(),
        ],
      ),
      IOSUiSettings(
        title: 'Cropper',
        aspectRatioPresets: [
          CropAspectRatioPreset.original,
          CropAspectRatioPreset.square,
          CropAspectRatioPresetCustom(), // IMPORTANT: iOS supports only one custom aspect ratio in preset list
        ],
      ),
      WebUiSettings(
        context: context,
      ),
    ],
  );

class CropAspectRatioPresetCustom implements CropAspectRatioPresetData {
  @override
  (int, int)? get data => (2, 3);

  @override
  String get name => '2x3 (customized)';
}
    
</details>

Credits