如何使用Croppr.js获取裁剪的图像?

时间:2018-07-04 00:34:45

标签: javascript angular typescript ionic3

我正在研究Ionic 3移动应用程序。在其中,我使用 Croppr.js 库在将图像上传到服务器之前裁剪图像。但我找不到获取裁剪图像的方法。这是我尝试过的代码

index.html

A

profile.component.ts

A

home.component.html

<link href="assets/css/croppr.min.css" rel="stylesheet" />
<script src="assets/js/croppr.min.js"></script>

ionViewDidLoad() { this._croppr = new Croppr('#croppr', { maxSize: [512, 512, 'px'], minSize: [128, 128, 'px'], onCropStart: this.onCropStart, onUpdate: this.onCropUpdate, onCropEnd: this.onCropEnd }) } onCropEnd(data): void { console.log("On Crop End: ", data); } onCropUpdate(data) { console.log("On Crop Update: ", data); } onCropStart(data) { console.log("crop start: ", data) } 方法仅返回裁剪图像的尺寸。不是裁剪的图像。有谁知道如何以 File base64 字符串的形式获取裁剪的图像?

2 个答案:

答案 0 :(得分:0)

If you are using ionic 3, then you can use @ionic-native/crop": "^4.7.0" plugin for image crop. I have used this plugin for image crop in ionic 3.

I have also used image cropping functionality in angular using "ng2-img-cropper" plugin. Refer below code which is used in angular project this will help you.
demo.ts :
import {ImageCropperComponent, CropperSettings, Bounds} from 'ng2-img-cropper';

 @ViewChild('cropper', undefined)
    cropper:ImageCropperComponent;  

constructor( private cropperSettings: CropperSettings ) {
        this.cropperSettings = new CropperSettings();
        this.cropperSettings.noFileInput = true;
    }

  // To browse image 
   fileChangeListener($event) {
        var image:any = new Image();
        var file:File = $event.target.files[0];
        var myReader:FileReader = new FileReader();
        var that = this;
        this.isfileOpen = true;
        myReader.onloadend = function (loadEvent:any) {
            image.src = loadEvent.target.result;
            that.cropper.setImage(image);
        };
        myReader.readAsDataURL(file);
    }

  //convert cropped base64 image to image
     var base64Blob = this.dataURItoBlob( file );

   /**
     * Function to convert base64 image 
    **/
    dataURItoBlob = ( dataURI ) => {
        var binary = atob( dataURI.split( ',' )[1] );
        var array = [];
        for ( var i = 0; i < binary.length; i++ ) {
            array.push( binary.charCodeAt( i ) );
        }
        return new Blob( [new Uint8Array( array )], { type: 'image/jpeg' } );
    }

demo.html :
<img-cropper #cropper [hidden]="!isfileOpen" [image]="data" [settings]="cropperSettings"></img-cropper> 
       <br>
       <div class="file-upload"  *ngIf="!isfileOpen">
         <input id="custom-input" accept="image/*" class="textCenter" type="file" (change)="fileChangeListener($event)">
       </div>

答案 1 :(得分:0)

找到了解决方案。

Hierarchy