[NgZorroAntdMobileModule] 使用ImagePicker组件上传图片并压缩

本文展示了如何在Angular应用中利用NgZorroAntdMobile的ImagePicker组件进行图片上传,并结合ngx-image-compress库进行图片压缩。通过在app.module.ts和app.component.ts中的配置和调用,实现了图片上传功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码:

app.module.ts

import { NgxImageCompressService } from 'ngx-image-compress';

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { NgZorroAntdMobileModule } from 'ng-zorro-antd-mobile';
import { NgxImageCompressService } from 'ngx-image-compress';

import { DemoImagePickerBasicComponent } from './app.component';

import { registerLocaleData } from '@angular/common';
import en from '@angular/common/locales/en';
registerLocaleData(en);

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    NgZorroAntdMobileModule,
    BrowserAnimationsModule,
  ],
  providers: [NgxImageCompressService],
  declarations: [DemoImagePickerBasicComponent],
  bootstrap: [DemoImagePickerBasicComponent],
})
export class AppModule {}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { NgxImageCompressService } from 'ngx-image-compress';
const data = [
  /*{},
  {
    url: 'https://zos.alipayobjects.com/rmsportal/hqQWgTXdrlmVVYi.jpeg',
  },*/
];

@Component({
  selector: 'demo-image-picker-basic',
  template: `

    <ImagePicker
      [files]="files"
      [multiple]="false" 
      [selectable]="files.length < 1"
      [capture]="true"
      (onChange)="fileChange($event)"
      (onImageClick)="imageClick($event)"
    ></ImagePicker>
    <br><br> 
    Original: Size: {{sizeOfOriginalImage | number : '1.2-2'}}MB
    <br>
    <img [src]="localUrl" height="200px">
    <br><br><br> 
    Compressed: Size: {{sizeOFCompressedImage | number : '1.2-2'}}MB<br>
    <img [src]="localCompressedURl" height="200px">
  `,
  styles: [
    `
      .ip-segment-wrapper {
        display: flex;
        border-radius: 5px;
        overflow: hidden;
        min-height: 27px;
        opacity: 1;
      }
      .ip-segment-btn {
        display: flex;
        flex: 1;
        justify-content: center;
        align-items: center;
        color: #108ee9;
        font-size: 14px;
        line-height: 1;
        -webkit-transition: background 0.2s;
        transition: background 0.2s;
        position: relative;
        border: 1px solid #108ee9;
        width: 100%;
        box-sizing: border-box;
        border-left-width: 0;
      }
      .ip-segment-btn.selected {
        background: #108ee9;
        color: #fff;
      }
      .ip-segment-btn:nth-child(1) {
        border-left-width: 1px;
        border-radius: 5px 0 0 5px;
      }
      .ip-segment-btn:nth-child(2) {
        border-left-width: 1px;
        border-radius: 0 5px 5px 0;
      }
    `,
  ],
})
export class DemoImagePickerBasicComponent implements OnInit {
  constructor(private imageCompress: NgxImageCompressService) {}
  file: any;
  localUrl: any;
  localCompressedURl: any;
  sizeOfOriginalImage: number;
  sizeOFCompressedImage: number;

  compressFile(image, fileName) {
    if (image == null) {
      this.localCompressedURl = image;
      this.sizeOfOriginalImage = null;
      this.sizeOFCompressedImage = null;
      return;
    }
    var imgResultAfterCompress: string;
    var orientation = -1;
    this.sizeOfOriginalImage =
      this.imageCompress.byteCount(image) / (1024 * 1024);
    console.warn('Size in bytes is now:', this.sizeOfOriginalImage);
    this.imageCompress
      .compressFile(image, orientation, 50, 50)
      .then((result) => {
        imgResultAfterCompress = result;
        this.localCompressedURl = result;
        this.sizeOFCompressedImage =
          this.imageCompress.byteCount(result) / (1024 * 1024);
        console.warn(
          'Size in bytes after compression:',
          this.sizeOFCompressedImage
        );
        // create file from byte
        const imageName = fileName;
        // call method that creates a blob from dataUri
        const imageBlob = this.dataURItoBlob(
          imgResultAfterCompress.split(',')[1]
        );
        //imageFile created below is the new compressed file which can be send to API in form data
        const imageFile = new File([result], imageName, { type: 'image/jpeg' });
      });
  }
  dataURItoBlob(dataURI) {
    const byteString = window.atob(dataURI);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array], { type: 'image/jpeg' });
    return blob;
  }

  ngOnInit() {}

  files = data.slice(0);

  fileChange(params) {
    console.log(params);
    const { files, type, index } = params;
    this.files = files;

    this.localUrl = this.files.length > 0 ? this.files[0].url : null;
    this.compressFile(this.localUrl, 'fileName');
  }

  imageClick(params) {
    console.log(params);
  }
}

生成效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值