在 Angular 项目中,你可以结合 ngx-compress-image
和 ngx-image-cropper
来实现图像压缩和裁剪的功能。以下是一个完整的示例,展示如何在 Angular 项目中使用这两个库。
ngx-compress-image
和 ngx-image-cropper
。使用 npm 安装这两个库:
npm install ngx-compress-image ngx-image-cropper
app.module.ts
中导入 NgxImageCompressService
和 ImageCropperModule
。// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgxImageCompressService } from 'ngx-compress-image';
import { ImageCropperModule } from 'ngx-image-cropper';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ImageCropperModule
],
providers: [NgxImageCompressService],
bootstrap: [AppComponent]
})
export class AppModule { }
ngx-compress-image
和 ngx-image-cropper
。// app.component.ts
import { Component } from '@angular/core';
import { NgxImageCompressService } from 'ngx-compress-image';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
imageChangedEvent: any = '';
croppedImage: any = '';
compressedImage: any = '';
constructor(private imageCompress: NgxImageCompressService) {}
fileChangeEvent(event: any): void {
this.imageChangedEvent = event;
}
imageCropped(event: any) {
this.croppedImage = event.base64;
}
compressImage() {
this.imageCompress.compressFile(this.croppedImage, -1, 50, 50).then(
result => {
this.compressedImage = result;
}
);
}
}
<!-- app.component.html -->
<div>
<input type="file" (change)="fileChangeEvent($event)" />
<image-cropper
[imageChangedEvent]="imageChangedEvent"
[maintainAspectRatio]="true"
[aspectRatio]="4 / 3"
format="png"
(imageCropped)="imageCropped($event)"
></image-cropper>
<div *ngIf="croppedImage">
<h3>Cropped Image</h3>
<img [src]="croppedImage" />
<button (click)="compressImage()">Compress Image</button>
</div>
<div *ngIf="compressedImage">
<h3>Compressed Image</h3>
<img [src]="compressedImage" />
</div>
</div>
app.module.ts
中导入 NgxImageCompressService
和 ImageCropperModule
。ngx-image-cropper
显示图像裁剪器,并处理裁剪事件。ngx-compress-image
压缩裁剪后的图像。png
或 jpeg
)。compressFile
方法的参数包括图像的质量和压缩比,你可以根据需要调整这些参数。领取专属 10元无门槛券
手把手带您无忧上云