Git Product home page Git Product logo

image_crop's Introduction

Image Cropping plugin for Flutter

A flutter plugin to crop image on iOS and Android.

Image Cropping Preview

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 cropped 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 working 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 efficient 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 a large image is to be loaded into the memory, there is a sampling function that relies on a native platform to proportionally scale down the image before 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. Prefer to leverage this functionality when displaying images in UI.

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

Once Crop widget is ready, there is a native support of cropping and scaling an image. In order to produce higher quality cropped image, rely on sampling image with preferred maximum width and height. Scale up a resolution of the sampled image. When cropped, the image is in higher resolution. Example is illustrated below:

final sampledFile = await ImageCrop.sampleImage(
    file: originalFile,
    preferredWidth: (1024 / crop.scale).round(),
    preferredHeight: (4096 / crop.scale).round(),
);

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

image_crop's People

Contributors

igorstr avatar lukbukkit avatar lykhonis avatar megz15 avatar radomir9720 avatar sh4wn avatar taslimisina avatar vmeretin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

image_crop's Issues

Initial render of crop area empty

Hello,

I've encountered a bug on my OnePlus 5T while using this library.
My phone currently runs Android 9, but this also happens with Android 8.
This bug doesn't appear in the Android emulator (8 and 9).

Bug: After I've choosen a picture, there's nothing displayed in the crop area, until I choose a new picture or request a crop.

Here's a video of the bug: https://youtu.be/ybkYCej60kQ
And other thing I've noticed: When I toggle the debug render mode, the image appears.
Here's a video of that: https://youtu.be/GvGAfBsTwxw

Thanks for the useful library πŸ‘

CGImageDestinationAddImage: cgImage is nil

hi, i use this plugin to crop image after capturing from camera it will corelate with ML rendering. its always show like below :

019-02-12 16:38:05.990634+0700 Runner[11066:1902438] flutter: com.apple.avfoundation.avcapturedevice.built-in_video:0
2019-02-12 16:38:05.991954+0700 Runner[11066:1902438] flutter: CameraLensDirection.back
2019-02-12 16:38:14.243699+0700 Runner[11066:1902438] flutter: image width : 1024 - image height : 1820
2019-02-12 16:38:14.246971+0700 Runner[11066:1902438] flutter: left span : 64.0
2019-02-12 16:38:14.247642+0700 Runner[11066:1902438] flutter: start crop image 1
2019-02-12 16:38:14.259076+0700 Runner[11066:1902433] CGImageDestinationAddImage:3247: *** ERROR: CGImageDestinationAddImage: cgImage is nil
2019-02-12 16:38:14.260092+0700 Runner[11066:1902433] finalize:2470: image destination must have at least one image

heres my code :

String imagePath = await Navigator.of(context).push(MaterialPageRoute(
      builder: (context){
        return CameraWrapper();
      }
    ));
    var image = await ImageCrop.sampleImage(
      file: File(imagePath),
      preferredWidth:  1024,
      preferredHeight: 1024
    );
    var options =  await ImageCrop.getImageOptions(
      file: image, 
    );
    
    print("image width : "+options.width.toString()+ " - image height : "+options.height.toString());

    double halfWidth = options.width / 2;
    double frameWidth = halfWidth + (halfWidth * 3 / 4);
    double frameHeight = (frameWidth * 10) / 16;
    print("left span : "+ ((options.width - frameWidth) / 2).toString());
    print("start crop image 1");
    try{
      image = await ImageCrop.cropImage(
        file: image,
        area: Rect.fromLTRB(0,10,0,10)
      );
    } on Exception catch(e){
      print("error cropping : "+ e.toString());
    }
    print("crop processing is done");

please correct me if i wrong. thanks

Incorrect initial scaling

Magnification is automatically set, although it is not necessary

Example:

Code:

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (_) => Scaffold(
      appBar: AppBar(),
      body: Crop.file(
        image,
        scale: 1,
        key: _cropKey,
        aspectRatio: 21 / 9,
      ),
    ),
  ),
);

Loaded image also contains aspect ratio 21 / 9
When page opens _cropKey.currentState.scale sets to 0.4, Although it could be 1.0

Aspect ratio problem

Setting an aspect ratio that is the same as the device screen causes the masking box to fill almost the whole screen and the handles are no longer selectable.

16:10 works fine
Screenshot_20190706-090703 1

10:16 fails, you can no longer move the handles
Screenshot_20190706-090642 1

Landscape mode does not work.

Hi everyone,
I have a problem with Landscape mode only (Screen width > height).
I use aspect ratio 1 is crop out of the screen in preview

Can everyone help me with this situation? Thanks.

Unhandled Exception:

Started to get this issue recently, everything was working fine before. Without any changes I m gettting this issue.

Image picker is already active error

I try to use camera with latest version (image_crop: ^0.3.0) and got an error on Image picker is already active. I used Samsung real device (S7 edge). Any idea?

D/ViewRootImpl@4c27af4MainActivity: ViewPostIme pointer 1
E/flutter (23312): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(already_active, Image picker is already active, null)
E/flutter (23312): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
E/flutter (23312): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
E/flutter (23312):
E/flutter (23312): #2 ImagePicker.pickImage (package:image_picker/image_picker.dart:53:40)
E/flutter (23312):
E/flutter (23312): #3 _MyAppState._openImage

Issue while running flutter build apk

I encounter an issue with the package when I try to build an APK with the "flutter build apk" command.
the error is:

                                                                        
* What went wrong:                                                      
Execution failed for task ':app:processReleaseResources'.               
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed                                    
     /Users/username/appLocation/android/app/src/main/AndroidManifest.xml:9:5-33:19: AAPT: error: attribute android:requestLegacyExternalStorage not found.
                                                                        
                                                                        
* Try:                                                                  
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
                                                                        
* Get more help at https://help.gradle.org                              
                                                                        
BUILD FAILED in 1m 34s                                                  
Running Gradle task 'assembleRelease'...                                
Running Gradle task 'assembleRelease'... Done                      95.0s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin image_crop...
Running Gradle task 'assembleAarRelease'...                             
Running Gradle task 'assembleAarRelease'... Done                    1.6s


FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'image_crop'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/Users/mohammadamir/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/image_crop-0.3.4/android/local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s


The plugin image_crop could not be built due to the issue above.

Errors when trying to crop image

W/ExifInterface(28582): Skip the tag entry since data format (ULONG) is unexpected for tag: LightSource W/ExifInterface(28582): Stop reading file since a wrong offset may cause an infinite loop: 0 I/chatty (28582): uid=10310(com.refereepro.refereepro_cm) pool-1-thread-1 identical 1 line W/ExifInterface(28582): Stop reading file since a wrong offset may cause an infinite loop: 0 W/ExifInterface(28582): Skip the tag entry since data format (ULONG) is unexpected for tag: LightSource W/ExifInterface(28582): Stop reading file since a wrong offset may cause an infinite loop: 0 I/chatty (28582): uid=10310(com.refereepro.refereepro_cm) pool-1-thread-1 identical 1 line W/ExifInterface(28582): Stop reading file since a wrong offset may cause an infinite loop: 0

I have a Samsung Galaxy A50. When trying to crop an image I always get an error, and although I don't know a way to know for sure, it always looks like the image was incorrectly cropped (if cropped at all). Happens exactly the same when trying to crop a picture from the Gallery.

Anyone knows what could be going on?

Cropping in screen section

Hello,
Thanks for the library is very useful!
I'm having some issues trying to crop an image without using the whole screen. For some reason the Crop widget doesn't respect its boundaries. Have you try using it like this? Is this an edge case? Or Im missing something?
Maybe with an screenshot I can explain it better. In the screenshot you can see as somehow the grid overflows the divider.
Screenshot_1587753930

Thanks!

Throwing Error when tried to open the same image again.

When tried to open the same image again the next time, below mentioned errors are thrown.

by going through the error I get is null error is thrown.

But I am clicking on an image only when it is being displayed in the gallery pick view, then how come a null object is thrown.

and if I choose a new image which was never chosen earlier there is no error thrown.

I/Timeline( 4543): Timeline: Activity_launch_request time:798925952 intent:Intent { act=android.intent.action.GET_CONTENT typ=image/* }
E/flutter ( 4543): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(INVALID, Image source cannot be opened, null)
E/flutter ( 4543): #0      StandardMethodCodec.decodeEnvelope 
E/flutter ( 4543): #1      MethodChannel.invokeMethod 
E/flutter ( 4543): <asynchronous suspension>
E/flutter ( 4543): #2      ImageCrop.sampleImage
E/flutter ( 4543): <asynchronous suspension>
E/flutter ( 4543): #3      _ImageDemoPageState._openImage
E/flutter ( 4543): <asynchronous suspension>
E/flutter ( 4543): #4      _ImageDemoPageState._buildOpenImage.<anonymous closure>
E/flutter ( 4543): #5      _InkResponseState._handleTap 
E/flutter ( 4543): #6      _InkResponseState.build.<anonymous closure> 
E/flutter ( 4543): #7      GestureRecognizer.invokeCallback 
E/flutter ( 4543): #8      TapGestureRecognizer._checkUp 
E/flutter ( 4543): #9      TapGestureRecognizer.handlePrimaryPointer 
E/flutter ( 4543): #10     PrimaryPointerGestureRecognizer.handleEvent 
E/flutter ( 4543): #11     PointerRouter._dispatch 
E/flutter ( 4543): #12     PointerRouter.route 
E/flutter ( 4543): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent 
E/flutter ( 4543): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent 
E/flutter ( 4543): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent 
E/flutter ( 4543): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue 
E/flutter ( 4543): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket 
E/flutter ( 4543): #18     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter ( 4543): #19     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4543): #20     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter ( 4543): #21     _invoke1 (dart:ui/hooks.dart:233:10)
E/flutter ( 4543): #22     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
E/flutter ( 4543):

Add the ability to crop a video

Hey, really nice package!

I was wondering if it's possible for you to add the ability to crop a video?
Like cropping an image, you show the video with a video player (better_player, video_player, etc...), while being able to pan and zoom the video.

You can make another widget (CropVideo) that accepts a video file.
When wanting to actually crop the video, you call the function VideoCrop.cropVideo.
Maybe add a function like VideoCrop.sampleVideo to make it a better resolution before cropping.

Please consider adding this feature.
Thank you!

How to save crop_image?

I need to save cropped image to app temp folder and use later to send via email. So I have a few question.

  1. How can I save cropped image to device?
  2. Separately I need to take 3 picture and crop the images before send via mail. what is the best and fastest way to save these images?

thanks

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

  // scale up to use maximum possible number of pixels
  // this will sample image in higher resolution to make cropped image larger
  final sample = await ImageCrop.sampleImage(
    file: _file,
    preferredSize: (3000 / scale).round(),
  );

  final file = await ImageCrop.cropImage(
    file: sample,
    area: area,
  );

Cropping area is not preserved if the scale is changed.

The plugin is great. However, I would like to change the scale of the image programmatically, i.e zoom in with the slider. However when I implement this, with Crop.file(file, aspectRatio: 1, scale: _sliderValue), the cropped image does not correspond to the selected area.

It's hard to zoom image (dragging instead)

Hi, thank you for your package.

I've found that on iOS it's hard to catch the zooming gesture (didn't check on Android). When you put 2 fingers on the screen in 9 cases of 10 it's considered as a drag gesture (like 1 finger).

Is it possible to improve this behavior?

How to use ImageCrop.cropImage alone?

This is my code:

import 'dart:io';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File _image;

  Future _getCroppedImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);

    final croppedFile = await ImageCrop.cropImage(
      file: image,
      area: Rect.fromLTRB(100, 250, 300, 350),
    );

    setState(() => _image = croppedFile);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child:
            _image == null ? Text('Please pick an image') : Image.file(_image),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getCroppedImage,
        child: Icon(Icons.image),
      ),
    );
  }
}

But after picking an image, program crashes! I only need to crop with certain area.
How can I fix this issue?

Crash cause call Result methods from a thread other than the main thread

When tried to open image.

E/AndroidRuntime( 7809): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: pool-12-thread-1 E/AndroidRuntime( 7809): at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:605) E/AndroidRuntime( 7809): at io.flutter.embedding.engine.FlutterJNI.invokePlatformMessageResponseCallback(FlutterJNI.java:556) E/AndroidRuntime( 7809): at io.flutter.embedding.engine.dart.DartMessenger$Reply.reply(DartMessenger.java:129) E/AndroidRuntime( 7809): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler$1.success(MethodChannel.java:215) E/AndroidRuntime( 7809): at com.lykhonis.imagecrop.ImageCropPlugin$1.run(ImageCropPlugin.java:120) E/AndroidRuntime( 7809): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) E/AndroidRuntime( 7809): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) E/AndroidRuntime( 7809): at java.lang.Thread.run(Thread.java:764)

My doctor.
Flutter (Channel master, v1.5.9-pre.167, on Microsoft Windows [Version 10.0.17763.437], locale en-US) β€’ Flutter version 1.5.9-pre.167 at C:\flutter β€’ Framework revision f5674d7098 (8 hours ago), 2019-05-06 18:32:28 -0700 β€’ Engine revision ee6412a74d β€’ Dart version 2.3.0 (build 2.3.0-dev.0.5 dbe80f3397)

look like this issue

Add an option for a static crop

First Thank you for the great work.
Can you please add an option to make the crop size static , just like with facebook profile picture , the user can only drag and move his picture inside a defined area but they can't change the size of the crop of this defined area.

Thanks and keep it up.

How can I use 16:9 type aspectRatio?

How can I use 16:9 type aspectRatio? I need the crop area be fixed and I need to move only image. I need rectangle type crop area to certain width and height. How can I do that?

child: Crop.file(
_sample,
key: cropKey,
alwaysShowGrid: true,
aspectRatio: 4.0 / 3.0,),

No image when moving to any grid corner when image scaled to max (2.0 by default)

No image (just black screen) when moving image to any grid corner (image corner as same position with grid corner) when it scaled to max (2.0 by default). Same effect when moving (both scaled and not) image, from one corner to opposite (for example from top/left corner to bottom/right corner). It happens when top left image corner past center of the crop view.

Not cropping images taken from samsung camera

This happens as it does not read meta data of the images. A portrait image is saved in landscape orientation and those details are saved as Exif. When a portrait image is given to the cropper it read its height and width in wrong orientation where width > height.

hello,there is another bug

If the target is a square picture,it will automatic zoom in to fit the height of the crop background,so there is always a part of the picture in the horizontal direction that is not visible.,and can't be selected.

ImageStreamLister not found

I am seeing errors in the debug console when i try use Crop.file about a missing image stream listener

Error: Type 'ImageStreamListener' not found.
ImageStreamListener _imageListener;
^^^^^^^^^^^^^^^^^^^
Error: 'ImageStreamListener' isn't a type.

Add several modes

There should be two modes
The first is to move the zoom image, but the clipping area is fixed.
Second, the image is fixed and the clipping area can be moved.
Then there are some problems.
Image zooming is not sensitive. I have found a code problem. Can I submit it it?
Pictures should not be forced to return, so that the corners are not easily intercepted, or returns should also be returned to the clipping area.

Not able to crop image

When I am calling ImageCrop.sampleImage it's crashing my application

Stop reading file since a wrong offset may cause an infinite loop: 0
E/AndroidRuntime(28321): FATAL EXCEPTION: pool-1-thread-1
E/AndroidRuntime(28321): Process: com.example.lokbol, PID: 28321
E/AndroidRuntime(28321): java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.app.Activity.getCacheDir()' on a null object reference
E/AndroidRuntime(28321): 	at com.lykhonis.imagecrop.ImageCropPlugin.createTemporaryImageFile(ImageCropPlugin.java:341)
E/AndroidRuntime(28321): 	at com.lykhonis.imagecrop.ImageCropPlugin.access$200(ImageCropPlugin.java:39)
E/AndroidRuntime(28321): 	at com.lykhonis.imagecrop.ImageCropPlugin$2.run(ImageCropPlugin.java:226)
E/AndroidRuntime(28321): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime(28321): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime(28321): 	at java.lang.Thread.run(Thread.java:764)
W/OPDiagnose(28321): getService:OPDiagnoseService NULL

Please consider these logs

Crop() widget not working

When try to use the widget with and without the aspectRation property, it always fails with a BoxConstraint.

`════════ Exception caught by rendering library ═════════════════════════════════════════════════════
The following assertion was thrown during performLayout():
BoxConstraints forces an infinite height.

These invalid constraints were provided to RenderSemanticsGestureHandler's layout() function by the following function, which probably computed the invalid constraints in question:
RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:259:13)
The offending constraints were: BoxConstraints(w=411.4, h=Infinity)
User-created ancestor of the error-causing widget was:
Crop-[LabeledGlobalKey#45848] file:///C:/Users/Filip/Desktop/Projekte/Diplomarbeit/listassist/lib/pages/picture-show.dart:182:15
When the exception was thrown, this was the stack:
#0 BoxConstraints.debugAssertIsValid..throwError (package:flutter/src/rendering/box.dart:501:9)
#1 BoxConstraints.debugAssertIsValid. (package:flutter/src/rendering/box.dart:548:21)
#2 BoxConstraints.debugAssertIsValid (package:flutter/src/rendering/box.dart:552:6)
#3 RenderObject.layout (package:flutter/src/rendering/object.dart:1618:24)
#4 RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:259:13)
...
The following RenderObject was being processed when the exception was fired: RenderConstrainedBox#a9775 relayoutBoundary=up3 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
... parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
... constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
... size: MISSING
... additionalConstraints: BoxConstraints(biggest)
RenderObject: RenderConstrainedBox#a9775 relayoutBoundary=up3 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
parentData: offset=Offset(0.0, 0.0); flex=null; fit=null (can use size)
constraints: BoxConstraints(0.0<=w<=411.4, 0.0<=h<=Infinity)
size: MISSING
additionalConstraints: BoxConstraints(biggest)
... child: RenderSemanticsGestureHandler#ae6f2 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
... parentData:
... constraints: MISSING
... size: MISSING
... gestures:
... child: RenderPointerListener#10954 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
... parentData:
... constraints: MISSING
... size: MISSING
... behavior: opaque
... listeners: down
... child: RenderCustomPaint#82cbb NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
... parentData:
... constraints: MISSING
... size: MISSING
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ (2) Exception caught by rendering library ═════════════════════════════════════════════════
RenderBox was not laid out: RenderConstrainedBox#a9775 relayoutBoundary=up3 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1681 pos 12: 'hasSize'
User-created ancestor of the error-causing widget was:
Center file:///C:/Users/Filip/Desktop/Projekte/Diplomarbeit/listassist/lib/pages/picture-show.dart:148:13
════════════════════════════════════════════════════════════════════════════════════════════════════`

My code:

            if (_imageFile != null) ...[
              Crop(
                key: cropKey,
                image: FileImage(_imageFile),
                aspectRatio: 4.0 / 3.0,
              ),
            ]

Rendering error when reducing the crop image

this is really a great plugin.
but there is a small issue, I can zoom out and move the crop image at the same time, so some times I drag it out of screen, and it won't come back automatically. the result is, screen is black,or rending a wrong texture.

i want moving cropper

hi genius developer.

i want make a moving cropper. please provide that function ??

please tell me the good news.

thank you ^^

Handles are moving the image

When handles are moved, the image is moved at the same time.
This makes it difficult to select a crop area.
However curiously the image does not move with the bottom-right handle.

Cropped image not perfect square with aspect ratio of 1

When cropping an image using aspectRatio: 1, the cropped image sometimes has a width that's 1px larger than its height.

Do you have any idea what's the cause of this bug, and if it's something we can fix in this package?

on release build apk crop widget seems container filled grey. on debug apk no problem.

I develop app on debug and crop widget works great.
But on release version of apk, crop widget seems complete grey box like below.

Screenshot_20201208-201840

I showing MyCustomCropWidget in stack with showCrop variable.

// Stack .. [...
// Camera Preview ,
Visibility(
              visible: showCrop,
              child: MyCustomCropWidget(
                imagePath: imagePath,
                clipOkay: clipOkay,
                deleteAllPhotos: () {
                  deleteAllPhotos();
                  setState(() {
                    showCrop = false;
                  });
                },
              ),
            )
// .... ] / stack
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_crop/image_crop.dart';
import 'package:path/path.dart';
import 'package:myapp/common/widgets/cancel_button.dart';
import 'package:myapp/helpers/file_helper.dart';

class MyCustomCropWidget extends StatefulWidget {
  final String imagePath;
  final Function clipOkay;
  final Function deleteAllPhotos;

  const MyCustomCropWidget(
      {Key key, this.imagePath, this.clipOkay, this.deleteAllPhotos})
      : super(key: key);
  @override
  _MyCustomCropWidgetState createState() => _MyCustomCropWidgetState();
}

class _MyCustomCropWidgetState extends State<MyCustomCropWidget> {
  final cropKey = GlobalKey<CropState>();

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
      child: Stack(
        children: [
          Container(
            padding: const EdgeInsets.all(20.0),
            child: Crop(
              key: cropKey,
              image: FileImage(File(widget.imagePath)),
//        aspectRatio: 4.0 / 3.0,
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Stack(
              children: [
                CancelButton(
                  onPressed: widget.deleteAllPhotos,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  child: Positioned.fill(
                    child: Align(
                      alignment: Alignment.center,
                      child: IconButton(
                        icon: Icon(Icons.check),
                        color: Colors.white,
                        iconSize: 60,
                        onPressed: () async {
                          print("Image Source for Crop: " + widget.imagePath);

                          final croppedImage = await ImageCrop.cropImage(
                            file: File(widget.imagePath),
                            area: cropKey.currentState.area,
                          );
                          print("cropped image path: " + croppedImage.path);

                          // delete original image.

                          await File(widget.imagePath).delete();

                          String fileLocation =
                              join(await FileHelper.localPath, "files/");
                          if (!(await Directory(fileLocation).exists()))
                            await Directory(fileLocation).create();

                          fileLocation =
                              join(fileLocation, basename(croppedImage.path));
                          await FileHelper.moveFile(
                              File(croppedImage.path), fileLocation);

                          widget.clipOkay(fileLocation);
                        },
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.