ng2-file-upload icon indicating copy to clipboard operation
ng2-file-upload copied to clipboard

How to use with image croppers?

Open kolkov opened this issue 7 years ago • 6 comments

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

kolkov avatar Oct 04 '16 16:10 kolkov

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, :-)

wallaceiam avatar Oct 19 '16 16:10 wallaceiam

Did anyone get this working?

onAfterAddingFile only seems to call after onCompleteItemCallback

and readAsDataURL needs a blob not a file.

any help appreciated.

RZR666 avatar Jul 24 '17 08:07 RZR666

Anyone has solution for this?

NeelBhatt avatar Oct 04 '18 10:10 NeelBhatt

<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 avatar Feb 08 '19 08:02 FURQAN2050

`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});
};

}`

FURQAN2050 avatar Feb 08 '19 08:02 FURQAN2050

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!

antoniusng avatar Nov 02 '22 11:11 antoniusng