### Image Cropping Example Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md Example demonstrating how to use ImageCropper to crop an image with platform-specific UI settings for Android, iOS, and Web. Includes custom aspect ratio presets. ```dart 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)'; } ``` -------------------------------- ### Complete Cross-Platform Image Cropper Example Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt This widget allows users to pick an image from their gallery or camera and then crop it. It includes platform-specific UI settings for Android, iOS, and Web. Ensure you have the image_picker and image_cropper packages added to your project. ```dart import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; class ImageCropperDemo extends StatefulWidget { @override State createState() => _ImageCropperDemoState(); } class _ImageCropperDemoState extends State { CroppedFile? _croppedFile; bool _isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Image Cropper Demo')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_croppedFile != null) ...[ Container( width: 300, height: 300, decoration: BoxDecoration( border: Border.all(color: Colors.grey), ), child: kIsWeb ? Image.network(_croppedFile!.path, fit: BoxFit.contain) : Image.file(File(_croppedFile!.path), fit: BoxFit.contain), ), SizedBox(height: 20), Text('Path: ${_croppedFile!.path}'), SizedBox(height: 20), ElevatedButton( onPressed: () => setState(() => _croppedFile = null), child: Text('Clear'), ), ] else if (_isLoading) CircularProgressIndicator() else Column( children: [ ElevatedButton.icon( icon: Icon(Icons.photo_library), label: Text('Pick & Crop from Gallery'), onPressed: () => _pickAndCrop(ImageSource.gallery), ), SizedBox(height: 16), ElevatedButton.icon( icon: Icon(Icons.camera_alt), label: Text('Take Photo & Crop'), onPressed: () => _pickAndCrop(ImageSource.camera), ), ], ), ], ), ), ); } Future _pickAndCrop(ImageSource source) async { setState(() => _isLoading = true); try { // Pick image final picker = ImagePicker(); final pickedFile = await picker.pickImage(source: source); if (pickedFile == null) { setState(() => _isLoading = false); return; } // Crop image final croppedFile = await ImageCropper().cropImage( sourcePath: pickedFile.path, compressFormat: ImageCompressFormat.jpg, compressQuality: 90, maxWidth: 1920, maxHeight: 1920, uiSettings: _buildUiSettings(), ); setState(() { _croppedFile = croppedFile; _isLoading = false; }); } catch (e) { setState(() => _isLoading = false); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error: $e')), ); } } List _buildUiSettings() { return [ AndroidUiSettings( toolbarTitle: 'Crop Image', toolbarColor: Theme.of(context).primaryColor, toolbarWidgetColor: Colors.white, backgroundColor: Colors.black, activeControlsWidgetColor: Theme.of(context).primaryColor, initAspectRatio: CropAspectRatioPreset.original, lockAspectRatio: false, cropStyle: CropStyle.rectangle, aspectRatioPresets: [ CropAspectRatioPreset.original, CropAspectRatioPreset.square, CropAspectRatioPreset.ratio4x3, CropAspectRatioPreset.ratio16x9, ], ), IOSUiSettings( title: 'Crop Image', doneButtonTitle: 'Done', cancelButtonTitle: 'Cancel', resetAspectRatioEnabled: true, aspectRatioLockEnabled: false, cropStyle: CropStyle.rectangle, aspectRatioPresets: [ CropAspectRatioPreset.original, CropAspectRatioPreset.square, CropAspectRatioPreset.ratio4x3, CropAspectRatioPreset.ratio16x9, ], ), WebUiSettings( context: context, presentStyle: WebPresentStyle.dialog, size: CropperSize(width: 500, height: 500), viewwMode: WebViewMode.mode_1, dragMode: WebDragMode.move, background: true, guides: true, center: true, rotatable: true, scalable: true, zoomable: true, translations: WebTranslations.en(), ), ]; } } ``` -------------------------------- ### Use Built-in Aspect Ratio Presets Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Utilize predefined aspect ratio presets for the crop menu. Includes common ratios like square, 4:3, 16:9, and the original image ratio. ```dart import 'package:image_cropper/image_cropper.dart'; // Use built-in presets final presets = [ CropAspectRatioPreset.original, // Original image ratio CropAspectRatioPreset.square, // 1:1 CropAspectRatioPreset.ratio3x2, // 3:2 CropAspectRatioPreset.ratio4x3, // 4:3 CropAspectRatioPreset.ratio5x3, // 5:3 CropAspectRatioPreset.ratio5x4, // 5:4 CropAspectRatioPreset.ratio7x5, // 7:5 CropAspectRatioPreset.ratio16x9, // 16:9 ]; // Get preset details for (final preset in presets) { print('Name: ${preset.name}'); print('Data: ${preset.data}'); // Returns (ratioX, ratioY) tuple or null for original } ``` -------------------------------- ### Crop Image with Custom Settings Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Launches the image cropping UI with specified source path and customization options for aspect ratio, compression, and platform-specific UI. Handles the result or cancellation. ```dart import 'package:image_cropper/image_cropper.dart'; Future cropImage(String imagePath) async { final croppedFile = await ImageCropper().cropImage( sourcePath: imagePath, maxWidth: 1080, maxHeight: 1080, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), compressFormat: ImageCompressFormat.jpg, compressQuality: 90, uiSettings: [ AndroidUiSettings( toolbarTitle: 'Crop Image', toolbarColor: Colors.deepOrange, toolbarWidgetColor: Colors.white, initAspectRatio: CropAspectRatioPreset.original, lockAspectRatio: false, ), IOSUiSettings( title: 'Crop Image', minimumAspectRatio: 1.0, ), WebUiSettings( context: context, presentStyle: WebPresentStyle.dialog, size: CropperSize(width: 500, height: 500), ), ], ); if (croppedFile != null) { print('Cropped image path: ${croppedFile.path}'); // Use the cropped image final bytes = await croppedFile.readAsBytes(); print('Image size: ${bytes.length} bytes'); } } ``` -------------------------------- ### Image Cropper Configuration Options Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md This section details the various options available for configuring the image cropper's behavior and appearance. ```APIDOC ## Image Cropper Configuration Options ### Description This section details the various options available for configuring the image cropper's behavior and appearance. ### Parameters #### Request Body Parameters (Configuration Options) - **zoomOnTouch** (bool) - Optional - Enable to zoom the image by dragging touch. Default = `true` - **zoomOnWheel** (bool) - Optional - Enable to zoom the image by mouse wheeling. Default = `true` - **wheelZoomRatio** (num) - Optional - Define zoom ratio when zooming the image by mouse wheeling. Default = `0.1` - **cropBoxMovable** (bool) - Optional - Enable to move the crop box by dragging. Default = `true` - **cropBoxResizable** (bool) - Optional - Enable to resize the crop box by dragging. Default = `true` - **toggleDragModeOnDblclick** (bool) - Optional - Enable to toggle drag mode between "crop" and "move" when clicking twice on the cropper. Default = `true` - **minContainerWidth** (num) - Optional - The minimum width of the container. Default = `200` - **minContainerHeight** (num) - Optional - The minimum height of the container. Default = `100` - **minCropBoxWidth** (num) - Optional - The minimum width of the crop box. Default = `0` - **minCropBoxHeight** (num) - Optional - The minimum height of the crop box. Default = `0` - **presentStyle** (WebPresentStyle) - Optional - Presentation style of cropper, either a dialog or a page (route). Default = `dialog` - **context** (BuildContext) - Required - Current BuildContext. The context is required to show cropper dialog or route - **customDialogBuilder** (WebDialogBuilder) - Optional - Builder to customize the cropper `Dialog` - **customRouteBuilder** (WebRouteBuilder) - Optional - Builder to customize the cropper `PageRoute` - **barrierColor** (Color) - Optional - Barrier color for displayed `Dialog` - **translations** (WebTranslations) - Optional - Translations to display - **themeData** (WebThemeData) - Optional - Control UI customization ### Request Example ```json { "zoomOnTouch": true, "cropBoxResizable": false, "minContainerWidth": 300, "context": "BuildContext" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **data** (object) - Contains the cropped image information or confirmation. #### Response Example ```json { "status": "success", "data": { "croppedImagePath": "/path/to/cropped/image.jpg" } } ``` ``` -------------------------------- ### ImageCropper.cropImage() Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Launches the image cropping UI with customizable settings. Returns a CroppedFile object or null if cancelled. ```APIDOC ## ImageCropper.cropImage() ### Description The main method to launch the image cropping UI. Takes a source image path and optional parameters for controlling the crop behavior and UI customization. Returns a `CroppedFile` object on success, or `null` if the user cancels the operation. ### Method `cropImage` ### Endpoint N/A (This is a method call within the Flutter plugin) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:image_cropper/image_cropper.dart'; Future cropImage(String imagePath) async { final croppedFile = await ImageCropper().cropImage( sourcePath: imagePath, maxWidth: 1080, maxHeight: 1080, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), compressFormat: ImageCompressFormat.jpg, compressQuality: 90, uiSettings: [ AndroidUiSettings( toolbarTitle: 'Crop Image', toolbarColor: Colors.deepOrange, toolbarWidgetColor: Colors.white, initAspectRatio: CropAspectRatioPreset.original, lockAspectRatio: false, ), IOSUiSettings( title: 'Crop Image', minimumAspectRatio: 1.0, ), WebUiSettings( context: context, presentStyle: WebPresentStyle.dialog, size: CropperSize(width: 500, height: 500), ), ], ); if (croppedFile != null) { print('Cropped image path: ${croppedFile.path}'); // Use the cropped image final bytes = await croppedFile.readAsBytes(); print('Image size: ${bytes.length} bytes'); } } ``` ### Response #### Success Response (200) - **CroppedFile** (object) - An object containing the path to the cropped image and methods to read its data. #### Response Example ```json { "path": "/path/to/cropped/image.jpg" } ``` ``` -------------------------------- ### Configure JPEG Image Compression Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Set compressFormat to ImageCompressFormat.jpg for smaller file sizes, suitable for photos. Adjust compressQuality (0-100) for quality-size trade-off. High quality settings are useful for print. ```dart import 'package:image_cropper/image_cropper.dart'; // JPEG output - smaller file size, good for photos final jpegCrop = await ImageCropper().cropImage( sourcePath: imagePath, compressFormat: ImageCompressFormat.jpg, compressQuality: 85, // 0-100, higher = better quality, larger file ); ``` ```dart // High quality JPEG for print final printQuality = await ImageCropper().cropImage( sourcePath: imagePath, compressFormat: ImageCompressFormat.jpg, compressQuality: 100, maxWidth: 4000, maxHeight: 4000, ); ``` ```dart // Optimized for web upload final webOptimized = await ImageCropper().cropImage( sourcePath: imagePath, compressFormat: ImageCompressFormat.jpg, compressQuality: 70, maxWidth: 1920, maxHeight: 1080, ); ``` -------------------------------- ### Process Cropped File Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Demonstrates how to process a CroppedFile object, accessing its path, reading its content as bytes or a string, and streaming its data. Includes platform-specific file operations for mobile. ```dart import 'dart:io'; import 'package:image_cropper/image_cropper.dart'; Future processCroppedFile(CroppedFile croppedFile) async { // Get the file path (use for display or mobile file operations) final String path = croppedFile.path; print('File path: $path'); // Read as bytes (works on all platforms including web) final Uint8List bytes = await croppedFile.readAsBytes(); print('Total bytes: ${bytes.length}'); // Read as base64 string final String content = await croppedFile.readAsString(); // Stream the file contents final Stream stream = croppedFile.openRead(); await for (final chunk in stream) { print('Read chunk of ${chunk.length} bytes'); } // On mobile, you can also use the path directly if (!kIsWeb) { final file = File(path); // Save to permanent location await file.copy('/path/to/permanent/location/cropped.jpg'); } } ``` -------------------------------- ### Define and Use Custom Aspect Ratio Presets Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Implement `CropAspectRatioPresetData` to create custom aspect ratio presets for app-specific ratios. These can be added to the crop menu alongside built-in presets. ```dart import 'package:image_cropper/image_cropper.dart'; // Define custom aspect ratio preset class InstagramPortraitPreset implements CropAspectRatioPresetData { @override String get name => '4x5 (Instagram Portrait)'; @override (int, int)? get data => (4, 5); } class CinemaWidePreset implements CropAspectRatioPresetData { @override String get name => '21:9 (Cinematic)'; @override (int, int)? get data => (21, 9); } class TwitterHeaderPreset implements CropAspectRatioPresetData { @override String get name => '3:1 (Twitter Header)'; @override (int, int)? get data => (3, 1); } // Use custom presets with built-in presets final croppedFile = await ImageCropper().cropImage( sourcePath: imagePath, uiSettings: [ AndroidUiSettings( toolbarTitle: 'Crop for Social Media', aspectRatioPresets: [ CropAspectRatioPreset.original, CropAspectRatioPreset.square, InstagramPortraitPreset(), CinemaWidePreset(), TwitterHeaderPreset(), ], ), IOSUiSettings( title: 'Crop for Social Media', aspectRatioPresets: [ CropAspectRatioPreset.original, CropAspectRatioPreset.square, InstagramPortraitPreset(), // Note: iOS supports only one custom preset ], ), ], ); ``` -------------------------------- ### Image Cropper Configuration Options Source: https://github.com/hnvn/flutter_image_cropper/blob/master/image_cropper/README.md This section details the various boolean and string properties available to customize the image cropper's UI and functionality. ```APIDOC ## Image Cropper Configuration ### Description This section details the various properties available to customize the image cropper's UI and functionality. ### Method N/A (Configuration options) ### Endpoint N/A (Configuration options) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This section describes the configurable properties for the image cropper. - **hidesNavigationBar** (bool) - Optional - If 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 presented. - **rotateButtonsHidden** (bool) - Optional - When enabled, hides the rotation button, as well as the alternative rotation button visible when `showClockwiseRotationButton` is set to YES (default is false). - **resetButtonHidden** (bool) - Optional - When enabled, hides the 'Reset' button on the toolbar (default is false). - **aspectRatioPickerButtonHidden** (bool) - Optional - When enabled, hides the 'Aspect Ratio Picker' button on the toolbar (default is false). - **resetAspectRatioEnabled** (bool) - Optional - If 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). - **aspectRatioLockDimensionSwapEnabled** (bool) - Optional - If 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). - **aspectRatioLockEnabled** (bool) - Optional - If 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). - **title** (String) - Optional - Title text that appears at the top of the view controller. - **doneButtonTitle** (String) - Optional - Title for the 'Done' button. Setting this will override the Default which is a localized string for "Done". - **cancelButtonTitle** (String) - Optional - Title for the 'Cancel' button. Setting this will override the Default which is a localized string for "Cancel". - **cropStyle** (CropStyle) - Optional - Controls the style of crop bounds, it can be rectangle or circle style (default is `CropStyle.rectangle`). - **aspectRatioPresets** (List) - Optional - Controls the list of aspect ratios in the crop menu view. ### Request Example ```json { "hidesNavigationBar": false, "rotateButtonsHidden": true, "title": "Crop Image", "cropStyle": "circle" } ``` ### Response #### Success Response (200) N/A (Configuration options) #### Response Example N/A (Configuration options) ``` -------------------------------- ### Initialize and Crop in Custom Dialog Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md When using WebDialogBuilder or WebRouteBuilder, ensure initCropper() is called to initialize the Cropper object and crop() is called to trigger the crop feature. The result is then returned using Navigator.of(context).pop(result). ```dart class CropperDialog extends StatefulWidget { ... } class _CropperDialogState extends State { @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, ); }, ... ) ``` -------------------------------- ### IOUiSettings Properties Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md The IOUiSettings class provides properties to customize the UI of the TOCropViewController library on iOS. ```APIDOC ## IOUiSettings Properties ### Description This section details the configurable properties within the `IOUiSettings` class for customizing the image cropping interface on iOS. ### Method N/A (Configuration Class) ### Endpoint N/A (Configuration Class) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## Configuration Properties ### minimumAspectRatio - **minimumAspectRatio** (double) - The minimum cropping aspect ratio. If set, the user is prevented from setting the cropping rectangle to a lower aspect ratio than defined by the parameter. ### rectX - **rectX** (double) - The initial rect of cropping: x-coordinate. ### rectY - **rectY** (double) - The initial rect of cropping: y-coordinate. ### rectWidth - **rectWidth** (double) - The initial rect of cropping: width. ### rectHeight - **rectHeight** (double) - The initial rect of cropping: height. ### showActivitySheetOnDone - **showActivitySheetOnDone** (bool) - If true, when the user hits 'Done', a `UIActivityController` will appear before the view controller ends. ### showCancelConfirmationDialog - **showCancelConfirmationDialog** (bool) - Shows a confirmation dialog when the user hits 'Cancel' and there are pending changes (default is false). ### rotateClockwiseButtonHidden - **rotateClockwiseButtonHidden** (bool) - When 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). ### embedInNavigationController - **embedInNavigationController** (bool) - Embed the presented `TOCropViewController` in a `UINavigationController` (default is false). ``` -------------------------------- ### WebUiSettings Properties Source: https://github.com/hnvn/flutter_image_cropper/blob/master/image_cropper/README.md The WebUiSettings class provides various properties to customize the appearance and behavior of the image cropper on the web. ```APIDOC ## WebUiSettings ### Description Provides a helper class `WebUiSettings` that wraps all properties for customizing the UI in the `cropperjs` library on the web. ### Properties #### `size` - **Type**: `CropperSize` - **Description**: Display size of the cropper. Default = `{ width: 500, height: 500 }` #### `viewwMode` - **Type**: `WebViewMode` - **Description**: Define the view mode of the cropper. Details of available options in [View Mode](#view-mode). Default = `0` #### `dragMode` - **Type**: `WebDragMode` - **Description**: Define the dragging mode of the cropper. Details of available options in [Drag Mode](#drag-mode). Default = `crop` #### `initialAspectRatio` - **Type**: `num` - **Description**: Define 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. #### `checkCrossOrigin` - **Type**: `bool` - **Description**: Check if the current image is a cross-origin. Default = `true`. #### `checkOrientation` - **Type**: `bool` - **Description**: Check 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 = `true`. #### `modal` - **Type**: `bool` - **Description**: Show the black modal above the image and under the crop box. Default = `true`. #### `guides` - **Type**: `bool` - **Description**: Show the dashed lines above the crop box. Default = `true`. #### `center` - **Type**: `bool` - **Description**: Show the center indicator above the crop box. Default = `true`. #### `highlight` - **Type**: `bool` - **Description**: Show the white modal above the crop box (highlight the crop box). Default = `true`. #### `background` - **Type**: `bool` - **Description**: Show the grid background of the container. Default = `true`. #### `movable` - **Type**: `bool` - **Description**: Enable to move the image. Default = `true`. #### `rotatable` - **Type**: `bool` - **Description**: Enable to rotate the image. Default = `true`. #### `scalable` - **Type**: `bool` - **Description**: Enable to scale the image. Default = `true`. #### `zoomable` - **Type**: `bool` - **Description**: Enable to zoom the image. Default = `true`. ``` -------------------------------- ### Configure Rectangle and Circle Crop Styles Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Use CropStyle.rectangle for general cropping and CropStyle.circle for profile pictures. Ensure correct UI settings for Android and iOS. ```dart import 'package:image_cropper/image_cropper.dart'; // Rectangle crop (default) - for general image cropping final rectangleCrop = await ImageCropper().cropImage( sourcePath: imagePath, uiSettings: [ AndroidUiSettings( cropStyle: CropStyle.rectangle, aspectRatioPresets: [ CropAspectRatioPreset.original, CropAspectRatioPreset.ratio16x9, ], ), IOSUiSettings( cropStyle: CropStyle.rectangle, ), ], ); ``` ```dart // Circle crop - ideal for profile pictures and avatars final circleCrop = await ImageCropper().cropImage( sourcePath: imagePath, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), // Lock to square uiSettings: [ AndroidUiSettings( cropStyle: CropStyle.circle, lockAspectRatio: true, ), IOSUiSettings( cropStyle: CropStyle.circle, aspectRatioLockEnabled: true, ), ], ); ``` -------------------------------- ### Using Custom Dialog Builder in WebUiSettings Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Integrate your custom dialog builder within the `WebUiSettings` by providing the `customDialogBuilder` callback. This callback receives the necessary cropper widgets and functions to build your custom UI. ```dart final croppedFile = await ImageCropper().cropImage( sourcePath: imagePath, uiSettings: [ WebUiSettings( context: context, size: CropperSize(width: 500, height: 500), customDialogBuilder: (cropper, initCropper, crop, rotate, scale) { return CustomCropperDialog( cropper: cropper, initCropper: initCropper, crop: crop, rotate: rotate, scale: scale, ); }, ), ], ); ``` -------------------------------- ### Include Cropper.js for Web Configuration Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Add the Cropper.js CSS and JavaScript files to your web/index.html file for web-based image cropping. ```html ``` -------------------------------- ### Configure Web UI Settings Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Customize the cropping UI on web platforms using Cropper.js options. Required for web targeting, supports dialog or page presentation styles with extensive behavior customization. ```dart import 'package:image_cropper/image_cropper.dart'; import 'package:flutter/material.dart'; // Basic web settings final webSettings = WebUiSettings( context: context, // Required: BuildContext for showing dialog/route presentStyle: WebPresentStyle.dialog, // Cropper display size size: CropperSize(width: 500, height: 500), // View mode (0-3, controls crop box constraints) viewwMode: WebViewMode.mode_1, // Restrict crop box to canvas // Drag mode dragMode: WebDragMode.crop, // 'crop', 'move', or 'none' // Initial aspect ratio (when not locked) initialAspectRatio: 1.0, // Cross-origin handling checkCrossOrigin: true, checkOrientation: true, // UI elements visibility modal: true, // Dark overlay guides: true, // Dashed lines center: true, // Center indicator highlight: true, // Highlight crop box background: true, // Grid background // Interaction controls movable: true, rotatable: true, scalable: true, zoomable: true, zoomOnTouch: true, zoomOnWheel: true, wheelZoomRatio: 0.1, cropBoxMovable: true, cropBoxResizable: true, toggleDragModeOnDblclick: true, // Minimum sizes minContainerWidth: 200, minContainerHeight: 100, minCropBoxWidth: 50, minCropBoxHeight: 50, // Translations for UI labels translations: WebTranslations( title: 'Crop Image', rotateLeftTooltip: 'Rotate Left', rotateRightTooltip: 'Rotate Right', cancelButton: 'Cancel', cropButton: 'Done', ), // Theme customization themeData: WebThemeData( rotateLeftIcon: Icons.rotate_left, rotateRightIcon: Icons.rotate_right, doneIcon: Icons.check, backIcon: Icons.arrow_back, rotateIconColor: Colors.white, scaleSliderMinValue: 0.5, scaleSliderMaxValue: 2.0, scaleSliderDivisions: 15, ), // Dialog barrier color barrierColor: Colors.black54, ); // Use in cropImage call final croppedFile = await ImageCropper().cropImage( sourcePath: imagePath, uiSettings: [webSettings], ); ``` -------------------------------- ### Custom Cropper Dialog Widget Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Define a custom StatefulWidget to build your own cropping dialog UI. Ensure you call `initCropper()` in `initState` and `crop()` when the apply button is pressed. ```dart import 'package:image_cropper/image_cropper.dart'; import 'package:flutter/material.dart'; class CustomCropperDialog extends StatefulWidget { final Widget cropper; final VoidCallback initCropper; final Future Function() crop; final void Function(RotationAngle) rotate; final void Function(num) scale; const CustomCropperDialog({ required this.cropper, required this.initCropper, required this.crop, required this.rotate, required this.scale, }); @override State createState() => _CustomCropperDialogState(); } class _CustomCropperDialogState extends State { double _scale = 1.0; @override void initState() { super.initState(); widget.initCropper(); // IMPORTANT: Must call this } @override Widget build(BuildContext context) { return Dialog( child: Container( width: 600, padding: EdgeInsets.all(16), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text('Custom Cropper', style: TextStyle(fontSize: 24)), SizedBox(height: 16), SizedBox( width: 500, height: 500, child: widget.cropper, ), SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( icon: Icon(Icons.rotate_left), onPressed: () => widget.rotate(RotationAngle.counterClockwise90), ), IconButton( icon: Icon(Icons.rotate_right), onPressed: () => widget.rotate(RotationAngle.clockwise90), ), SizedBox(width: 20), Text('Scale:'), Slider( value: _scale, min: 0.5, max: 2.0, onChanged: (value) { setState(() => _scale = value); widget.scale(value); }, ), ], ), SizedBox(height: 16), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('Cancel'), ), SizedBox(width: 8), ElevatedButton( onPressed: () async { // IMPORTANT: Call crop() and return result final result = await widget.crop(); Navigator.pop(context, result); }, child: Text('Apply'), ), ], ), ], ), ), ); } } ``` -------------------------------- ### WebUiSettings Properties Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md The WebUiSettings class provides various properties to customize the UI of the image cropper on the web. These properties are used to configure the cropperjs library. ```APIDOC ## WebUiSettings ### Description Provides a helper class called `WebUiSettings` that wraps all properties that can be used to customize the UI in the `cropperjs` library for web applications. ### Properties #### `size` - **Type**: CropperSize - **Description**: Display size of the cropper. Default = `{ width: 500, height: 500 }` #### `viewwMode` - **Type**: WebViewMode - **Description**: Define the view mode of the cropper. Details of available options in [View Mode](#view-mode). Default = `0` #### `dragMode` - **Type**: WebDragMode - **Description**: Define the dragging mode of the cropper. Details of available options in [Drag Mode](#drag-mode). Default = `crop` #### `initialAspectRatio` - **Type**: num - **Description**: Define the initial aspect ratio of the crop box. Only available when the `aspectRatio` option is set to NaN. Default = `NaN` #### `checkCrossOrigin` - **Type**: bool - **Description**: Check if the current image is a cross-origin image. Default = `true` #### `checkOrientation` - **Type**: bool - **Description**: Check 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 = `true` #### `modal` - **Type**: bool - **Description**: Show the black modal above the image and under the crop box. Default = `true` #### `guides` - **Type**: bool - **Description**: Show the dashed lines above the crop box. Default = `true` #### `center` - **Type**: bool - **Description**: Show the center indicator above the crop box. Default = `true` #### `highlight` - **Type**: bool - **Description**: Show the white modal above the crop box (highlight the crop box). Default = `true` #### `background` - **Type**: bool - **Description**: Show the grid background of the container. Default = `true` #### `movable` - **Type**: bool - **Description**: Enable to move the image. Default = `true` #### `rotatable` - **Type**: bool - **Description**: Enable to rotate the image. Default = `true` #### `scalable` - **Type**: bool - **Description**: Enable to scale the image. Default = `true` #### `zoomable` - **Type**: bool - **Description**: Enable to zoom the image. Default = `true` ``` -------------------------------- ### Configure PNG Image Compression Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Use ImageCompressFormat.png for lossless compression, ideal for graphics requiring transparency. Note that compressQuality is ignored for PNG on the web. ```dart // PNG output - lossless, good for graphics with transparency final pngCrop = await ImageCropper().cropImage( sourcePath: imagePath, compressFormat: ImageCompressFormat.png, // Note: compressQuality is ignored for PNG on web ); ``` -------------------------------- ### Configure UCropActivity for Android Source: https://context7.com/hnvn/flutter_image_cropper/llms.txt Add the UCropActivity to your AndroidManifest.xml file. This is required for the image cropping functionality on Android. ```xml ``` -------------------------------- ### Include Cropper.js in HTML Head Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md Add these lines within the `` tag of your `web/index.html` file to include the necessary CSS and JavaScript for Cropper.js. ```html .... .... ``` -------------------------------- ### Add UCropActivity to AndroidManifest.xml Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md Include the UCropActivity in your AndroidManifest.xml file to enable image cropping functionality. Ensure the theme is set appropriately. ```xml ``` -------------------------------- ### AndroidUiSettings Properties Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md Customize the UI of the image cropper on Android using the AndroidUiSettings class. This class wraps properties to customize the uCrop library's UI. ```APIDOC ## AndroidUiSettings Customization ### Description Provides a helper class `AndroidUiSettings` to customize the UI of the uCrop library on Android. ### Properties #### Toolbar Properties - **`toolbarTitle`** (String) - Description: Desired text for the Toolbar title. - **`toolbarColor`** (Color) - Description: Desired color of the Toolbar. - **`toolbarWidgetColor`** (Color) - Description: Desired color of Toolbar text and buttons (default is darker orange). #### Status Bar Properties - **`statusBarLight`** (bool) - Description: Set to true for a light status bar (dark icons), false for a dark status bar (light icons). #### Navigation Bar Properties - **`navBarLight`** (bool) - Description: Set to true for a light navigation bar (dark icons), false for a dark navigation bar (light icons). #### Color Properties - **`backgroundColor`** (Color) - Description: Desired background color that should be applied to the root view. - **`activeControlsWidgetColor`** (Color) - Description: Desired resolved color of the active and selected widget and progress wheel middle line (default is white). - **`dimmedLayerColor`** (Color) - Description: Desired color of the dimmed area around the crop bounds. - **`cropFrameColor`** (Color) - Description: Desired color of the crop frame. - **`cropGridColor`** (Color) - Description: Desired color of the crop grid/guidelines. #### Crop Grid and Frame Properties - **`cropFrameStrokeWidth`** (int) - Description: Desired width of the crop frame line in pixels. - **`cropGridRowCount`** (int) - Description: Crop grid rows count. - **`cropGridColumnCount`** (int) - Description: Crop grid columns count. - **`cropGridStrokeWidth`** (int) - Description: Desired width of the crop grid lines in pixels. - **`showCropGrid`** (bool) - Description: Set to true if you want to see a crop grid/guidelines on top of an image. #### Aspect Ratio Properties - **`lockAspectRatio`** (bool) - Description: Set to true if you want to lock the aspect ratio of crop bounds with a fixed value (locked by default). - **`initAspectRatio`** (CropAspectRatioPreset) - Description: Desired aspect ratio is applied (from the list of given aspect ratio presets) when starting the cropper. - **`aspectRatioPresets`** (List) - Description: Controls the list of aspect ratios in the crop menu view. #### Control Visibility - **`hideBottomControls`** (bool) - Description: Set to true to hide the bottom controls (shown by default). #### Crop Style - **`cropStyle`** (CropStyle) - Description: Controls the style of crop bounds, it can be rectangle or circle style (default is `CropStyle.rectangle`). ``` -------------------------------- ### Image Cropper Configuration Properties Source: https://github.com/hnvn/flutter_image_cropper/blob/master/README.md This section details the configurable properties for the Flutter Image Cropper, allowing for customization of the UI and functionality. ```APIDOC ## Image Cropper Configuration Properties This section details the configurable properties for the Flutter Image Cropper, allowing for customization of the UI and functionality. ### Properties - **hidesNavigationBar** (bool) - Optional - If 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 presented. - **rotateButtonsHidden** (bool) - Optional - When enabled, hides the rotation button, as well as the alternative rotation button visible when `showClockwiseRotationButton` is set to YES (default is false). - **resetButtonHidden** (bool) - Optional - When enabled, hides the 'Reset' button on the toolbar (default is false). - **aspectRatioPickerButtonHidden** (bool) - Optional - When enabled, hides the 'Aspect Ratio Picker' button on the toolbar (default is false). - **resetAspectRatioEnabled** (bool) - Optional - If 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). - **aspectRatioLockDimensionSwapEnabled** (bool) - Optional - If 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). - **aspectRatioLockEnabled** (bool) - Optional - If 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). - **title** (String) - Optional - Title text that appears at the top of the view controller. - **doneButtonTitle** (String) - Optional - Title for the 'Done' button. Setting this will override the Default which is a localized string for "Done". - **cancelButtonTitle** (String) - Optional - Title for the 'Cancel' button. Setting this will override the Default which is a localized string for "Cancel". - **cropStyle** (CropStyle) - Optional - Controls the style of crop bounds, it can be rectangle or circle style (default is `CropStyle.rectangle`). - **aspectRatioPresets** (List) - Optional - Controls the list of aspect ratios in the crop menu view. ```