Image cropping plugin

Thanks for your help.
I had to import it via import Cropper = require('cropperjs');, then it’s working ‘out of the box’.

1 Like

Hey, another question. I have a similar code like you for my image except that I have to call bypassSecurityTrustResourceUrl in the src. In the constructor I set the imageB64-variable with the base64-string. This starts an infinit loop calling the imageLoaded()-function. Don’t you have the same problem? Really strange, because the src is only set once.
I have the image in a Modal, maybe this is the problem…

Edit: Ok, I had to encapsulate the bypass-function. It’s working now…

Does anyone know where to find a working plugin for VIDEO CROPPING?

hi , I just wanted to ask… can we use ng2-img-cropper in ionic 2 ?? or is there a downside to it so that we have to use a plugin !!

Hey there. Your code here has helped me a lot to get this plugin working in an Ionic project. I’m having an issue trying to get the final cropped image. I’m getting a return of null on the getCroppedCanvas() method. Did you run into this issue at all?

Sounds like you are calling getCroppedCanvas() before imageLoaded() function.
make sure you do it AFTER.

Adding my own list of all the steps required to get cropperjs working with ionic-cordova-camera. Thanks to @reedrichards for showing the way.

system info

    Cordova CLI: 7.0.1 
    Ionic Framework Version: 3.2.1
    Ionic CLI Version: 3.0.0-beta.5
    ios-deploy version: 1.9.0 
    ios-sim version: 5.0.11 
    OS: macOS Sierra
    Node Version: v6.3.1
    Xcode version: Xcode 8.3.2 Build version 8E2002
```
**command line**
```
cordova plugin add cordova-plugin-camera

npm install cropperjs@^1.0.0-alpha --save
npm install cordova-plugin-camera@^2.4.1 --save 
npm install @types/cropperjs@0.0.26 --save-dev
```

**component file**
```
import { Component, ViewChild, ElementRef } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera';
import Cropper from 'cropperjs';

@Component({
  selector: 'page-example',
  templateUrl: 'example.html'
})
export class ExamplePage {
  @ViewChild('imageSrc') imageElement: ElementRef;

  getCameraOptions() {
    // just an example working config
    let cameraOpts: CameraOptions = {
      quality: 50,
      destinationType: this.camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.CAMERA,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      allowEdit: false,
      correctOrientation: true
    }

    return cameraOpts;
  }

  constructor(public camera: Camera) {
    this.camera.getPicture(this.getCameraOptions()).then((imageData) => {
      
      // this was the only way i was able to dynamically change the source
      this.imageElement.nativeElement.src = imageData;
      this.cropImage();
    }, (error) => {
      // do what you want
    });
  }

  cropImage() {
    this.cropperInstance = new Cropper(this.imageElement.nativeElement, {
        aspectRatio: 1 / 1, // square
        dragMode: 'move',
        modal: true,
        guides: false,
        highlight: false,
        background: false,
        autoCrop: true,
        autoCropArea: 0.9,
        responsive: false,
        zoomable: false,
        movable: false
    });
  }

  cropDone() {
    let croppedImg = this.cropperInstance.getCroppedCanvas({ width: 500, height: 500}).toDataURL('image/jpeg');

    // do whatever you want with base64 variable croppedImg
  }
}
```

**template file**
```
<ion-content>
  <button ion-button (click)="cropDone()">
    crop done
  </button>

  <img #imageSrc />
</ion-content>
```

**css**

I did it the easy way and copied cropperjs css contents to page-specific scss file.
The file is located at *node_modules/cropperjs/dist/cropper.css*
3 Likes

@thounie coolio, congrats and thx for the example!

You know why, I get this error:
main.js:82011 Error: Uncaught (in promise): TypeError: Cannot read property ‘crop’ of undefined
TypeError: Cannot read property ‘crop’ of undefined. ? thanks.

Quick question on this. I got the cropper working and I can set the correct size and all of that, but how do I make the cropper go away when I am done? I have tried calling

this.cropperInstance.clear();
this.cropperInstance.disable();
and
this.cropperInstance.destroy();

only the last one actually removes the cropper from the page, but then I lose the image. I want the user to be able to select an image, crop it, click done, and have the cropped image be the image source of the image tag on the display, and the cropper stuff should be gone from the display. When I call .clear() it kind of removes it, but doesn’t all the way. I just need to remove all the cropper stuff and have the cropped image be on the screen when done. Please, please help me out on this. I went through their docs and they show you how to start it up, and how to get the image data, but not how to shut it down after the user is done cropping the image. Thank you

Unfortunately I have no idea how to actually hide the cropper.

I have image handler (including cropper) on its own page that also has status bar hidden to give some more space. That way when I have done cropping I just handle the image and after that pop the page away.

Thanks a lot for your example Thounie. I’ll try your code tonight :slight_smile:

Thanku @richardmarais
great work!
very helpfull
:+1:

Anyone got Cropperjs working with Ionic 3?

I’ve been through all the solutions in this thread but end up with,

private cropper: Cropper; << [ts] cannot find name ‘Cropper’.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import  Cropper  from 'cropperjs';

@IonicPage()
@Component({
  selector: 'page-crop',
  templateUrl: 'crop.html',
})
export class CropPage {
  @ViewChild('imageSrc') imageElement: ElementRef;
  croppedImg:any;
  cropperInstance: any;
  constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) {
  }
  ionViewWillEnter() {
    //
     let cropI = this.navParams.get('cropdata');
     console.log(cropI)
     this.imageElement.nativeElement.src=cropI;

  }
  cropImage(){


  this.cropperInstance= new Cropper(this.imageElement.nativeElement, {
           aspectRatio: 4 / 3, // square
           dragMode: 'move',
           modal: true,
           guides: true,
           highlight: false,
           background: false,
           autoCrop: true,
           autoCropArea: 0.9,
           responsive: true,
           zoomable: true,
           movable: false
       });



  console.log(this.cropperInstance)

  }
  cropDone() {

  let croppedImg = this.cropperInstance.getCroppedCanvas({ width: 500, height: 500}).toDataURL('image/jpeg');

  this.viewCtrl.dismiss(croppedImg);
}
}

working

@physedo where does cropDone() get called?

EDIT: OK, I see now that the load event on the img element calls cropDone()

When using your same code, the only thing that is not working is when I call the getCroppedCanvas().toDataURL(), I get an image that is correct dimensions, but is totally black (or whatever color I set for the “transparent” color).

Any ideas why I don’t get the actual cropped image?

 cropperLoad(){
        console.log('cropper load',this.input.nativeElement);
        this.cropper = null;
        this.cropper = new Cropper(this.input.nativeElement,{
            dragMode:'move',
            aspectRatio:1,
            viewMode:1,
            zoomable:true,
            zoomOnWheel:false
            // crop:(e:Cropper.CropperCropEvent)=>{console.log(e)}
        })
    }

save(){
 this.croppedB64 = this.cropper.getCroppedCanvas({
            maxWidth:300,
            maxHeight:300,
            fillColor: 'red'
        }).toDataURL('image/jpeg',1); //THIS IMAGE IS SOLID BLACK
}

Hi I have the same problem do you mind telling me what you have edited please?

Sorry my bad . I did not add css to the page hence crop was not working

can anyone share one example snippet !!

I am getting this error

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 3
In ‘const’ enum declarations member initializer must be constant expression.

   L2:  export   const  enum  DragMode {
   L3:    Crop = 'crop',
   L4:    Move = 'move',

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 4
In ‘const’ enum declarations member initializer must be constant expression.

   L3:  Crop = 'crop',
   L4:  Move = 'move',
   L5:  None = 'none',

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 5
In ‘const’ enum declarations member initializer must be constant expression.

   L4:    Move = 'move',
   L5:    None = 'none',

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 16
In ‘const’ enum declarations member initializer must be constant expression.

  L15:  export const  enum ImageSmoothingQuality {
  L16:    Low = 'low',
  L17:    Medium = 'medium',

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 17
In ‘const’ enum declarations member initializer must be constant expression.

  L16:  Low = 'low',
  L17:  Medium = 'medium',
  L18:  High = 'high',

[18:14:49] typescript: node_modules/cropperjs/types/index.d.ts, line: 18
In ‘const’ enum declarations member initializer must be constant expression.

  L17:    Medium = 'medium',
  L18:    High = 'high',

version is Cropperjs :- 1.3.4
@types/cropperjs : 1.1.3

Hey, if you are looking for an example of image cropping in an ionic 3 app you should check https://ionicthemes.com/tutorials/about/ionic-2-image-handling

And for a tutorial that shows how to crop and image and then upload it to firebase check https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload

Hope it helps