首页 > 语言 > JavaScript > 正文

Angular使用 ng-img-max 调整浏览器中的图片的示例代码

2024-05-06 15:12:46
字体:
来源:转载
供稿:网友

你想在Angular应用程序中进行图片上传,是否想在图片上传之前在前端限制上传图片的尺寸?ng2-img-max模块正是你所要的! ng2-img-max模块会使用web sorkers 进行图片大小的计算,并驻留在主线程中。

我们来看看他的用途:

安装

首先,使用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,以便canvas.toBlob()可以在Safari和旧版本的Internet Explorer等浏览器上使用。

将polyfill脚本包含在项目中。 如果您使用Angular CLI,您可以将脚本添加到.angular-cli.json文件中:

//: .angular-cli.json..."scripts": [ "../node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.min.js"],//...

将脚本添加到Angular CLI配置后,您将需要重新启动本地服务。

现在我们将模块导入应用模块或功能模块:

//: 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); })}

如果您有多个图像需要一次性调整大小,请改用resize方法,并将图片文件数组作为第一个参数传入。

结果是Blob类型,但是如果需要,可以使用File构造函数将其转换为正确的文件:

//: app.component.tsuploadedImage: File;constructor(private ng2ImgMax: Ng2ImgMaxService) {}onImageChange(event){ let image = event.target.files[0];  this.ng2ImgMax.resizeImage(image,400,300).subscribe(result=> {  this.uploadedImage = new File([result],result.name); }, error=> {  console.log('error',error); })}

您现在可以将文件上传到您的后端。 不要忘记在后端做好验证,因为这里的内容会阻止一些用户将超大或非图像文件直接上传到后端。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选