Image-cropper binding

11 views
Skip to first unread message

ವಿದ್ಯಾಸಾಗರ್ ನಾಗಲಿಕರ್

unread,
Aug 16, 2019, 7:03:13 AM8/16/19
to Angular and AngularJS discussion

I am using image-cropper control to crop image in angular, but I am facing issue in binding the image to that control.

 image-cropper uses the two properties to bind the image

1)      imageChangedEvent:It will accept the input type as event(like file event).

    

OR


2)      imageBase64:It will accepts image as base64 data.

 

But I am having image src like ‘./Images/abd.png’

 

So how to bind the image to image-cropper using image src.

Sander Elias

unread,
Aug 21, 2019, 12:52:56 AM8/21/19
to Angular and AngularJS discussion
Hi ವಿದ್ಯಾಸಾಗರ್,

Use a service to do the conversion:
something like this will probably work:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { fromObservableObserverthrowError } from 'rxjs';
import { catchErrorswitchMap } from 'rxjs/operators';

export const fileRead = (blob: Blob=>
  new Observable((inner: Observer<string>=> {
    if (!(blob instanceof Blob)) {
      inner.error(new Error('`blob` must be an instance of File or Blob.'));
      return;
    }
    const fr = new FileReader();
    const resultHandler = r => {
      inner.next(r.target.result as string);
      inner.complete();
    };
    const errorHandler = e => inner.error(e);
    fr.addEventListener('load'resultHandler);
    fr.addEventListener('error'errorHandler);
    fr.readAsDataURL(blob);
    return () => {
      /** make sure to release the events so the filereader can be garbage collected */
      fr.removeEventListener('load'resultHandler);
      fr.removeEventListener('error'errorHandler);
    };
  });

@Injectable({
  providedIn'root'
})
export class ImageToUrlDataService {
  constructor(private http: HttpClient) {}

  convert(url: string) {
    return this.http.get(url, { responseType'blob' }).pipe(
      switchMap(fileRead),
      catchError(err => {
        console.error(err);
        return throwError(err);
      })
    );
  }
}

see it in action

regards
Sander
Reply all
Reply to author
Forward
0 new messages