image_crop 0.1.1

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 87

Image Cropping plugin for Flutter

A flutter plugin to crop image on iOS and Android.

Image Cropping Active Image Cropping Idle

The plugin comes with a Crop widget. The widget renders only image, overlay, and handles to crop an image. Thus it can be composed with other widgets to build custom image cropping experience.

The plugin is working with files to avoid passing large amount of data through method channels. Files are stored in cache folders of iOS and Android. Thus if there is a need to save actual croped image, ensure to copy the file to other location.

All of the computation intensive work is done off a main thread via dispatch queues on iOS and cache thread pool on Android.

Note: This plugin is still under development, some features are not available yet and testing has been limited.

Installation

Add image_crop image_crop as a dependency in pubspec.yaml.

Using

Create a widget to load and edit an image:

final cropKey = GlobalKey<CropState>();

Widget _buildCropImage() {
  return Container(
      color: Colors.black,
      padding: const EdgeInsets.all(20.0),
      child: Crop(
        key: cropKey,
        image: Image.file(imageFile),
        aspectRatio: 4.0 / 3.0,
      ),
  );
}

Access cropping values:

  • scale is a factor to proportionally scale image's width and height when cropped. 1.0 is no scale needed.
  • area is a rectangle indicating fractional positions on the image to crop from.
final crop = cropKey.currentState;
// or
// final crop = Crop.of(context);
final scale = crop.scale;
final area = crop.area;

if (area == null) {
    // cannot crop, widget is not setup
    // ...
}

Accessing and workign with images. As a convenience function to request permissions to access photos.

final permissionsGranted = await ImageCrop.requestPermissions();

Read image options, such as: width and height. This is efficent implementation that does not decode nor load actual image into a memory.

final options = await getImageOptions(file: file);
debugPrint('image width: ${options.width}, height: ${options.height}');

If image is large to be loaded into the memory, there is a sampling function that relies on a native platform to proportionally scale down the image befor loading it to the memory. e.g. resample image to get down to 1024x4096 dimension as close as possible. If it is a square preferredSize can be used to specify both width and height.

final sampleFile = await ImageCrop.sampleImage(
    file: originalFile,
    preferredWidth: 1024,
    preferredHeight: 4096,
);

Once Crop widget is ready, there is a native support of croping and scaling an image.

final croppedFile = await ImageCrop.cropImage(
    file: originalFile,
    scale: crop.scale,
    area: crop.area,
);

0.1.1

  • Fixed an exception when aspect ratio is not supplied
  • Updated README with more information and screenshots

0.1.0

  • Tools to resample by a factor, crop, and get options of images
  • Display image provider
  • Scale and crop image via widget
  • Optional aspect ratio of crop area

example/lib/main.dart

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_crop/image_crop.dart';

// Hidden import to let `flutter packages pub publish --dry-run` complete without errors
// FIXME: uncomment to try out example code
// import 'package:image_picker/image_picker.dart';

void main() {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarBrightness: Brightness.dark,
    statusBarIconBrightness: Brightness.light,
    systemNavigationBarIconBrightness: Brightness.light,
  ));

  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final cropKey = GlobalKey<CropState>();
  File _file;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Container(
          color: Colors.black,
          padding: const EdgeInsets.symmetric(vertical: 40.0, horizontal: 20.0),
          child: _file == null ? _buildOpeningImage() : _buildCroppingImage(),
        ),
      ),
    );
  }

  Widget _buildOpeningImage() {
    return Center(child: _buildOpenImage());
  }

  Widget _buildCroppingImage() {
    return Column(
      children: <Widget>[
        Expanded(
          child: Crop.file(
            _file,
            key: cropKey,
          ),
        ),
        Container(
          padding: const EdgeInsets.only(top: 20.0),
          alignment: AlignmentDirectional.center,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              FlatButton(
                child: Text(
                  'Crop Image',
                  style: Theme.of(context).textTheme.button.copyWith(color: Colors.white),
                ),
                onPressed: () => _cropImage(),
              ),
              _buildOpenImage(),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildOpenImage() {
    return FlatButton(
      child: Text(
        'Open Image',
        style: Theme.of(context).textTheme.button.copyWith(color: Colors.white),
      ),
      onPressed: () => _openImage(),
    );
  }

  Future<void> _openImage() async {
    final file = await ImagePicker.pickImage(source: ImageSource.gallery);
    final sample = await ImageCrop.sampleImage(file: file, preferredSize: 2000);

    setState(() {
      _file = sample;
    });
  }

  Future<void> _cropImage() async {
    final scale = cropKey.currentState.scale;
    final area = cropKey.currentState.area;
    if (area == null) {
      // cannot crop, widget is not setup
      return;
    }

    final file = await ImageCrop.cropImage(file: _file, area: area, scale: scale);
    debugPrint('$file');
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  image_crop: ^0.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:image_crop/image_crop.dart';
  
Version Uploaded Documentation Archive
0.1.1 Oct 20, 2018 Go to the documentation of image_crop 0.1.1 Download image_crop 0.1.1 archive
0.1.0 Oct 17, 2018 Go to the documentation of image_crop 0.1.0 Download image_crop 0.1.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
73
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
87
Learn more about scoring.

We analyzed this package on Nov 14, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.6
  • Flutter: 0.11.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test