How to use with image croppers? #434

Open
opened 2016-10-04 16:00:17 +00:00 by kolkov · 6 comments
kolkov commented 2016-10-04 16:00:17 +00:00 (Migrated from github.com)

Hi!
How to use with image croppers like this:
https://github.com/cstefanache/angular2-img-cropper

Hi! How to use with image croppers like this: https://github.com/cstefanache/angular2-img-cropper
wallaceiam commented 2016-10-19 16:22:25 +00:00 (Migrated from github.com)

Hi kolkov,

It is pretty simple with angular2-img-cropper

<input type="file" ng2FileSelect value="Select" [uploader]="uploader" />
<img-cropper #profileCropper [image]="data" [settings]="profileCropperSettings"></img-cropper>
<br>
<span class="result rounded" *ngIf="data.image">
<img [src]="data.image" [width]="profileCropperSettings.croppedWidth" [height]="profileCropperSettings.croppedHeight">
</span>
export class Images implements OnInit {
    image: any;
    data: any;
    profileCropperSettings: CropperSettings;
    uploader: FileUploader = new FileUploader({});
    hasBaseDropZoneOver: boolean = false;
    hasAnotherDropZoneOver: boolean = false;

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

    @ViewChild('profileEditorModal') profileEditorModal:ModalDirective;

    constructor() {
        this.profileCropperSettings = new CropperSettings();
        this.profileCropperSettings.noFileInput = true;

        this.data = {};
    }

    ngOnInit() {
        this.uploader.onAfterAddingFile = f => { <---- Handle when the uploader gets a new file
            this.image = new Image();
            var file: File = f._file;//e.target.files[0];
            var fileReader: FileReader = new FileReader();
            var that = this;
            fileReader.onloadend = function (loadEvent: any) {
                that.image.src = loadEvent.target.result;
                that.profileCropper.setImage(that.image);   <---- This seems to be where the magic happens
            };

            fileReader.readAsDataURL(file);
        }
   }
}
...

It was a bit of trial and error but hope that helps, :-)

Hi kolkov, It is pretty simple with [angular2-img-cropper](https://github.com/cstefanache/angular2-img-cropper) ``` <input type="file" ng2FileSelect value="Select" [uploader]="uploader" /> <img-cropper #profileCropper [image]="data" [settings]="profileCropperSettings"></img-cropper> <br> <span class="result rounded" *ngIf="data.image"> <img [src]="data.image" [width]="profileCropperSettings.croppedWidth" [height]="profileCropperSettings.croppedHeight"> </span> ``` ``` export class Images implements OnInit { image: any; data: any; profileCropperSettings: CropperSettings; uploader: FileUploader = new FileUploader({}); hasBaseDropZoneOver: boolean = false; hasAnotherDropZoneOver: boolean = false; @ViewChild('profileCropper', undefined) profileCropper: ImageCropperComponent; @ViewChild('profileEditorModal') profileEditorModal:ModalDirective; constructor() { this.profileCropperSettings = new CropperSettings(); this.profileCropperSettings.noFileInput = true; this.data = {}; } ngOnInit() { this.uploader.onAfterAddingFile = f => { <---- Handle when the uploader gets a new file this.image = new Image(); var file: File = f._file;//e.target.files[0]; var fileReader: FileReader = new FileReader(); var that = this; fileReader.onloadend = function (loadEvent: any) { that.image.src = loadEvent.target.result; that.profileCropper.setImage(that.image); <---- This seems to be where the magic happens }; fileReader.readAsDataURL(file); } } } ... It was a bit of trial and error but hope that helps, :-) ```
RZR666 commented 2017-07-24 08:50:30 +00:00 (Migrated from github.com)

Did anyone get this working?

onAfterAddingFile only seems to call after onCompleteItemCallback

and readAsDataURL needs a blob not a file.

any help appreciated.

Did anyone get this working? onAfterAddingFile only seems to call after onCompleteItemCallback and readAsDataURL needs a blob not a file. any help appreciated.
NeelBhatt commented 2018-10-04 10:32:11 +00:00 (Migrated from github.com)

Anyone has solution for this?

Anyone has solution for this?
FURQAN2050 commented 2019-02-08 08:11:35 +00:00 (Migrated from github.com)

<ion-row > <ion-col *ngIf="!organization.imageName"> <img-cropper #cropper [image]="data1" [settings]="cropperSettings"></img-cropper> <br> <!-- <span class="result rounded" *ngIf="data1.image" > <img [src]="data1.image" [width]="cropperSettings.croppedWidth" [height]="cropperSettings.croppedHeight"> </span> --> <ion-button size="small" (click)="uploadAll(data1.image)" >upload</ion-button> </ion-col> </ion-row>

` <ion-row > <ion-col *ngIf="!organization.imageName"> <img-cropper #cropper [image]="data1" [settings]="cropperSettings"></img-cropper> <br> <!-- <span class="result rounded" *ngIf="data1.image" > <img [src]="data1.image" [width]="cropperSettings.croppedWidth" [height]="cropperSettings.croppedHeight"> </span> --> <ion-button size="small" (click)="uploadAll(data1.image)" >upload</ion-button> </ion-col> </ion-row> `
FURQAN2050 commented 2019-02-08 08:11:49 +00:00 (Migrated from github.com)

`uploadAll(image){
console.log('func call',image);
this.croppedImage=image;
this.uploader.uploadAll();
}
upload() {
var image;//file upload methods
this.uploader.onAfterAddingFile = (item) => {
console.info('After adding a file', item,this.data1);
this.image = new Image();
var fileReader: FileReader = new FileReader();
var that = this;
fileReader.onloadend = function (loadEvent: any) {
that.image.src = loadEvent.target.result;
that.cropper.setImage(that.image);
console.log(that.data1);
};
fileReader.readAsDataURL(item._file);
};
this.uploader.onBeforeUploadItem=(item:any)=>{

  console.log(this.croppedImage)
  var blob = dataURItoBlob(this.croppedImage);
  item._file = blob;
  console.log('on beofre uploading item done')
}
this.uploader.onCompleteItem = (item, response: any, status, headers) => {
  console.info('Complete', response);
  response = JSON.parse(response);
  this.organization.imageName = response.result.files.file[0].name;
  this.organization.field = response.result.files.file[0].field;
  this.organization.container = response.result.files.file[0].container;
  this.organization.originalFilename = response.result.files.file[0].originalFilename;
  this.organization.size = response.result.files.file[0].size;
  this.organization.type = response.result.files.file[0].type;
  console.log('organization after uploading an image', this.organization);
};

var dataURItoBlob = function(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var array = [];
  for(var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {type: mimeString});
};

}`

`uploadAll(image){ console.log('func call',image); this.croppedImage=image; this.uploader.uploadAll(); } upload() { var image;//file upload methods this.uploader.onAfterAddingFile = (item) => { console.info('After adding a file', item,this.data1); this.image = new Image(); var fileReader: FileReader = new FileReader(); var that = this; fileReader.onloadend = function (loadEvent: any) { that.image.src = loadEvent.target.result; that.cropper.setImage(that.image); console.log(that.data1); }; fileReader.readAsDataURL(item._file); }; this.uploader.onBeforeUploadItem=(item:any)=>{ console.log(this.croppedImage) var blob = dataURItoBlob(this.croppedImage); item._file = blob; console.log('on beofre uploading item done') } this.uploader.onCompleteItem = (item, response: any, status, headers) => { console.info('Complete', response); response = JSON.parse(response); this.organization.imageName = response.result.files.file[0].name; this.organization.field = response.result.files.file[0].field; this.organization.container = response.result.files.file[0].container; this.organization.originalFilename = response.result.files.file[0].originalFilename; this.organization.size = response.result.files.file[0].size; this.organization.type = response.result.files.file[0].type; console.log('organization after uploading an image', this.organization); }; var dataURItoBlob = function(dataURI) { var binary = atob(dataURI.split(',')[1]); var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type: mimeString}); }; }`
antoniusng commented 2022-11-02 11:56:46 +00:00 (Migrated from github.com)

I would like to share my solution.

  1. Add event listeners for onFileDrop and change
<div class="profile-picture" *ngIf="uploader" >
  <img *ngIf="url" src="{{url}}" />
  <label *ngIf="editmode" for="uploader-input" ng2FileDrop class="uploader-drop" [ngClass]="{'drag-over': hasDragOver}" (fileOver)="fileOver($event)" [uploader]="uploader"

 (onFileDrop)="onFileDrop($event)"
 >
    <div class="infotext" *ngIf="!url" >{{initial | getInitial}}</div>
  </label>
  <input *ngIf="editmode" type="file" ng2FileSelect [uploader]="uploader" id="uploader-input" style="display:none" 

(change)="onFileChange($event)" 
/>
</div>
  1. Set those events on Image Cropper element (imageChangedEvent & imageFile)
    <image-cropper


      [imageChangedEvent]="imgChangeEvt"
      [imageFile]="imageFile"
      (imageCropped)="cropImage($event)"


      [maintainAspectRatio]="true"
      [aspectRatio]="4 / 4"
      [resizeToWidth]="256"
      format="png"
      (imageLoaded)="imgLoad()"
      (cropperReady)="initCropper()"
      (loadImageFailed)="imgFailed()">
    </image-cropper>

  1. At javascript, add the fields and methods accordingly. Set imageFile during onFileDrop event, and set imgChangeEvt during onFileChange. Also add another method to store the cropped image.
  imgChangeEvt: any = '';
  imageFile: any = null;
  cropped: any = '';

  onFileDrop(event: any): void {
    this.imgChangeEvt = '';
    this.imageFile=event[0];
  }

  onFileChange(event: any): void {
    this.imageFile=null;
    this.imgChangeEvt = event;
  }

  cropImage(e: ImageCroppedEvent) {
    this.cropped = e.base64;
  }
  1. Set autoUpload to false when instantiate FileUploader

      this.uploader = new FileUploader({
        url: SERVER_URL,
        disableMultipart: false,
        autoUpload: false,
        authToken: 'Bearer:'+token
      });
  1. Add method to upload the cropped image
uploadCroppedImage():void {
  if (!this.uploader || !this.uploader.queue || !this.uploader.queue.length)
    return;

  const idx = this.uploader.queue.length - 1;
  const fileItem:any = this.uploader.queue[idx];
  const file:File | null = this.shared.dataURLtoFile(this.cropped, fileItem.file.name);
  if (!file)
    return;
  this.uploader.queue[idx] = new FileItem(this.uploader, file, this.uploader.options);
  this.uploader.uploadAll();
}

Hope this will help!

I would like to share my solution. 1. Add event listeners for **onFileDrop** and **change** ``` <div class="profile-picture" *ngIf="uploader" > <img *ngIf="url" src="{{url}}" /> <label *ngIf="editmode" for="uploader-input" ng2FileDrop class="uploader-drop" [ngClass]="{'drag-over': hasDragOver}" (fileOver)="fileOver($event)" [uploader]="uploader" (onFileDrop)="onFileDrop($event)" > <div class="infotext" *ngIf="!url" >{{initial | getInitial}}</div> </label> <input *ngIf="editmode" type="file" ng2FileSelect [uploader]="uploader" id="uploader-input" style="display:none" (change)="onFileChange($event)" /> </div> ``` 2. Set those events on Image Cropper element (imageChangedEvent & imageFile) ``` <image-cropper [imageChangedEvent]="imgChangeEvt" [imageFile]="imageFile" (imageCropped)="cropImage($event)" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" [resizeToWidth]="256" format="png" (imageLoaded)="imgLoad()" (cropperReady)="initCropper()" (loadImageFailed)="imgFailed()"> </image-cropper> ``` 3. At javascript, add the fields and methods accordingly. Set imageFile during onFileDrop event, and set imgChangeEvt during onFileChange. Also add another method to store the cropped image. ``` imgChangeEvt: any = ''; imageFile: any = null; cropped: any = ''; onFileDrop(event: any): void { this.imgChangeEvt = ''; this.imageFile=event[0]; } onFileChange(event: any): void { this.imageFile=null; this.imgChangeEvt = event; } cropImage(e: ImageCroppedEvent) { this.cropped = e.base64; } ``` 4. Set autoUpload to false when instantiate FileUploader ``` this.uploader = new FileUploader({ url: SERVER_URL, disableMultipart: false, autoUpload: false, authToken: 'Bearer:'+token }); ``` 5. Add method to upload the cropped image ``` uploadCroppedImage():void { if (!this.uploader || !this.uploader.queue || !this.uploader.queue.length) return; const idx = this.uploader.queue.length - 1; const fileItem:any = this.uploader.queue[idx]; const file:File | null = this.shared.dataURLtoFile(this.cropped, fileItem.file.name); if (!file) return; this.uploader.queue[idx] = new FileItem(this.uploader, file, this.uploader.options); this.uploader.uploadAll(); } ``` Hope this will help!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: dc/ng2-file-upload#434