在Angular中,使用 ng-img-max 调整浏览器中的图片
我们来看看他的用途: 安装首先,使用npm 或 Yarn安装模块: $ npm install ng2-img-max blueimp-canvas-to-blob --save # or Yarn : $ yarn add ng2-img-max blueimp-canvas-to-blob blueimp-canvas-to-blob是一个polyfill,以便 将polyfill脚本包含在项目中。 如果您使用Angular CLI,您可以将脚本添加到.angular-cli.json文件中: //: .angular-cli.json ... "scripts": [ "../node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.min.js" ],//...
现在我们将模块导入应用模块或功能模块: //: app.module.ts //... import { Ng2ImgMaxModule } from 'ng2-img-max'; @NgModule({ declarations: [ AppComponent ],imports: [ //... ng2ImgMaxModule ],providers: [],bootstrap: [ AppComponent ] }) export class AppModule {} 最后,ng2-img-max服务可以导入并注入到这样的组件中: import { Component } from '@angular/core'; import { Ng2ImgMaxService } from 'ng2-img-max'; @Component({ ... }) export class AppComponent { constructor(private ng2ImgMax: Ng2ImgMaxService ) {} } 使用我们添加一个File文件输入框到组件的模板中,像这样: <input type='file' (change)="onImageChange($event)" accept="image/*" /> 在组件类中添加方法onImageChange,它将会限制图片的宽高为:400px,300px: updateImage: Blob; constructor(private ng2ImgMax: Ng2ImgMaxService) {} onImageChange(event){ let image = event.target.files[0]; this.ng2ImgMax.resizeImage(image,400,300).subscribe(result=> { this.uploadImage = result; },error=> { console.log('error:',error); }) }
结果是Blob类型,但是如果需要,可以使用File构造函数将其转换为正确的文件: //: app.component.ts uploadedImage: File; constructor(private ng2ImgMax: Ng2ImgMaxService) {} onImageChange(event){ let image = event.target.files[0]; this.ng2ImgMax.resizeImage(image,300).subscribe(result=> { this.uploadedImage = new File([result],result.name); },error=> { console.log('error',error); }) }
只限制宽度或高度假设您只想将高度限制为300px,并相应调整宽度,以保持宽高比相同。 只要设置任何一阀值到10000: //... onImageChange(event) { let image = event.target.files[0]; this.ng2ImgMax.resizeImage(image,10000,error); }); } 压缩代替Resizing您还可以使用compress或compressImage方法执行有损压缩,而不是调整图像大小。 只需传递最大值(兆字节)。 你显然想要运行一些测试,看看你想要走多远的几个小时,同时保持图像看起来很好。 在以下示例中,我们将生成的图像限制为大约75Kb: onImageChange(event) { let image = event.target.files[0]; this.ng2ImgMax.compressImage(image,0.075).subscribe( result => { this.uploadedImage = new File([result],result.name); this.getImagePreview(this.uploadedImage); },error => { console.log(' |