Angular里使用(image-compressor.js)图片压缩

参考资料:

http://www.imooc.com/article/40038

https://github.com/xkeshi/image-compressor

 示例代码:

1 <nz-upload class="avatar-uploader" [nzAccept]="'image/*'" nzFileType="image/png,image/jpeg,image/gif,image/jpg" [nzAction]="uploadPictureUrl" nzName="avatar" nzListType="picture-card" [nzShowUploadList]="false" [nzCustomRequest]="uploadImp" (nzChange)="handleChange($event)">
2                 <ng-container *ngIf="!imageUrl">
3                     <i nz-icon nzType="picture" nzTheme="outline"></i>
4                     <div class="ant-upload-text">上传</div>
5                 </ng-container>
6                 <img *ngIf="imageUrl" [src]="imageUrl" class="avatar" style="width:100px;height: 100px;">
7             </nz-upload>
8             <p>请上传jpg, gif, png格式的图片。建议图片尺寸&nbsp;宽:90px;高:90px</p>
 1 import ImageCompressor from 'image-compressor.js'
 2 
 3 
 4 // 自定义上传方法的实现
 5   uploadImp = async (item) => {
 6     debugger
 7     const isJPG = item.file.type.indexOf('image') > -1;
 8     if (!isJPG) {
 9       this.message.error('只能上传图片文件!');
10       return;
11     }
12     // 进行图片压缩
13     const compressionFile = await new ImageCompressor().compress(item.file, {
14       quality: .8,
15       maxWidth: 1000,
16       maxHeight: 1000,
17       convertSize: 614400, //超过600kb压缩
18       success(result) {
19       },
20       error(e) {
21         console.log(e);
22         debugger
23         throw { message: `压缩失败${e.message}` }
24       }
25     }).then(ret => {
26       debugger
27       console.log(ret);
28       item.file = ret;
29       if (ret.size > 600 * 1024) throw { message: '压缩后的图片不能超过600KB' };
30     }).catch((err) => {
31       const msg = err.message ? err.message : err;
32       this.message.error(`图片上传失败,请重试:${msg}`);
33     });

猜你喜欢

转载自www.cnblogs.com/24klr/p/11591890.html