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


Posted in Javascript onAugust 17, 2017

你想在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.ts

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

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

只限制宽度或高度

假设您只想将高度限制为300px,并相应调整宽度,以保持宽高比相同。 只要设置任何一阀值到10000:

//...
onImageChange(event) {
 let image = event.target.files[0];
 this.ng2ImgMax.resizeImage(image,10000,300).subscribe(result=> {
  this.uploadedImage = new File([result],result.name);
 },
 error=> {
  console.log('error:',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('? Oh no!', error);
  }
 );
}

图片预览

您可能想要预览要上传到用户的图像。 您可以使用FileReader对象执行此操作。 您还需要使用Angular的DomSanitizer来使其信任使用FileReader对象创建的base64编码数据URI:

现在,我们的组件内容是这样的。组件中有趣的新方法是getImagePreview:

//: app.component.ts

import { Component } from '@angular/core';
import { Ng2ImgMaxService } from 'ng2-img-max';
import { DomSanitizer } from '@angular/platform-browser';

@Component({ ... })
export class AppComponent {
 uploadedImage: File;
 imagePreview: string;

 constructor(
  private ng2ImgMax: Ng2ImgMaxService,
  public sanitizer: DomSanitizer
 ) {}

 onImageChange(event) {
  let image = event.target.files[0];

  this.ng2ImgMax.resizeImage(image, 10000, 375).subscribe(
   result => {
    this.uploadedImage = new File([result], result.name);
    this.getImagePreview(this.uploadedImage);
   },
   error => {
    console.log('? Oh no!', error);
   }
  );
 }

 getImagePreview(file: File) {
  const reader: FileReader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
   this.imagePreview = reader.result;
  };
 }
}

在我们的模板中,我们可以使用sanitizer来显示如图像:

//: app.component.html

<img
  *ngIf="imagePreview"
  [src]="sanitizer.bypassSecurityTrustUrl(imagePreview)">

这就是它的全部! 您还可以查看同一作者的ng2-img-tools包,以获得更多的浏览器端图像处理(如裁剪)。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript flash下fromCharCode和charCodeAt方法使用说明
Jan 12 Javascript
Asp.Net alert弹出提示信息的几种方法总结
Jan 29 Javascript
JavaScript面向对象的实现方法小结
Apr 14 Javascript
js控制网页前进和后退的方法
Jun 08 Javascript
javascript实现根据iphone屏幕方向调用不同样式表的方法
Jul 13 Javascript
Vue组件实例间的直接访问实现代码
Aug 20 Javascript
详解一个基于react+webpack的多页面应用配置
Jan 21 Javascript
Vue指令v-for遍历输出JavaScript数组及json对象的常见方式小结
Feb 11 Javascript
Vue编写可显示周和月模式的日历 Vue自定义日历内容的显示
Jun 26 Javascript
VUE注册全局组件和局部组件过程解析
Oct 10 Javascript
js实现查询商品案例
Jul 22 Javascript
JavaScript 对象创建的3种方法
Nov 17 Javascript
Canvas放置反弹效果随机图形(实例)
Aug 17 #Javascript
js实现方块上下左右移动效果
Aug 17 #Javascript
JavaScript中一些特殊的字符运算
Aug 17 #Javascript
在 Angular 中使用Chart.js 和 ng2-charts的示例代码
Aug 17 #Javascript
JS 中LocalStorage和SessionStorage的使用
Aug 17 #Javascript
jQuery的时间datetime控件在AngularJs中的使用实例(分享)
Aug 17 #jQuery
详解JS中的柯里化(currying)
Aug 17 #Javascript
You might like
如何过滤高亮显示非法字符
2006/10/09 PHP
windows下配置apache+php+mysql时出现问题的处理方法
2014/06/20 PHP
分享ThinkPHP3.2中关联查询解决思路
2015/09/20 PHP
php断点续传之文件分割合并详解
2016/12/13 PHP
Javascript生成json的函数代码(可以用php的json_decode解码)
2012/06/11 Javascript
jQuery.Validate验证库的使用介绍
2013/04/26 Javascript
jquery+css3打造一款ajax分页插件(自写)
2014/06/18 Javascript
jQuery实现鼠标滑过链接控制图片的滑动展开与隐藏效果
2015/10/28 Javascript
Bootstrap登陆注册页面开发教程
2016/07/12 Javascript
Vue.JS入门教程之处理表单
2016/12/01 Javascript
Bootstrap如何激活导航状态
2017/03/22 Javascript
浅谈react-native热更新react-native-pushy集成遇到的问题
2017/09/30 Javascript
vue学习教程之带你一步步详细解析vue-cli
2017/12/26 Javascript
解决vue 项目引入字体图标报错、不显示等问题
2018/09/01 Javascript
JavaScript实现表单注册、表单验证、运算符功能
2018/10/15 Javascript
js实现全选反选不选功能代码详解
2019/04/24 Javascript
elementUI同一页面展示多个Dialog的实现
2020/11/19 Javascript
js加减乘除精确运算方法实例代码
2021/01/17 Javascript
[02:56]DOTA2矮人直升机 英雄基础教程
2013/11/26 DOTA
Python类的多重继承问题深入分析
2014/11/09 Python
Python引用类型和值类型的区别与使用解析
2017/10/17 Python
快速入门python学习笔记
2017/12/06 Python
对Python实现简单的API接口实例讲解
2018/12/10 Python
python使用Plotly绘图工具绘制气泡图
2019/04/01 Python
Python namedtuple命名元组实现过程解析
2020/01/08 Python
Pandas把dataframe或series转换成list的方法
2020/06/14 Python
Python使用文件操作实现一个XX信息管理系统的示例
2020/07/02 Python
科茨沃尔德家居商店:Scotts of Stow
2018/06/29 全球购物
意大利珠宝店:Luxury Zone
2019/01/05 全球购物
献爱心活动总结
2014/05/07 职场文书
中学生检讨书1000字
2014/10/28 职场文书
面试通知短信
2015/04/20 职场文书
2015年财政局工作总结
2015/05/21 职场文书
小学三年级语文教学反思
2016/03/03 职场文书
Python实现批量自动整理文件
2022/03/16 Python
Java 垃圾回收超详细讲解记忆集和卡表
2022/04/08 Java/Android