Ritagliare immagini con Angular
Per ritargliare le immagini in Angular possiamo usare la libreria ngx-image-cropper.
Molto facile da usare e implementare, possiamo installarla tramite npm:
npm install ngx-image-cropper
Poi la prima cosa da fare è richiamare il modulo dentro app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {ImageCropperModule} from 'ngx-image-cropper';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ImageCropperModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
Dentro al nostro component:
import {Component} from '@angular/core';
import {ImageCroppedEvent} from 'ngx-image-cropper';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
imgChangeEvt: any = '';
cropImgPreview: any = '';
onFileChange(event: any): void {
this.imgChangeEvt = event;
}
onImageCropped(e: ImageCroppedEvent) {
this.cropImgPreview = e.base64;
console.log(this.cropImgPreview);
}
onImageLoaded() {
}
onCropperReady() {
}
onLoadImageFailed() {
}
}
Se guardate bene il base64 cambia nel momento in cui fate il cropped e/o spostate il cropped.
Questo l'HTML:
<input type="file" (change)="onFileChange($event)">
<br>
<image-cropper
[imageChangedEvent]="imgChangeEvt"
[maintainAspectRatio]="true"
[aspectRatio]="4 / 4"
[resizeToWidth]="256"
format="png"
(imageCropped)="onImageCropped($event)"
(imageLoaded)="onImageLoaded()"
(cropperReady)="onCropperReady()"
(loadImageFailed)="onLoadImageFailed()">
</image-cropper>
<hr>
<img [src]="cropImgPreview">
Vi rimane solo inviare il file al db e/ al filesystem; cosa che esula dal tutorial, in quanto richiede anche una parte lato server.
Enjoy!
javascript angular ngx-image-cropper
Commentami!