Ionic 3 + Angular Image Cropper

作者: 与蟒唯舞 | 来源:发表于2018-04-08 18:16 被阅读55次
    开始
    ionic start ionic3-image-crop blank
    cd ionic3-image-crop
    
    安装插件与第三方库
    ionic cordova plugin add cordova-plugin-camera
    npm install @ionic-native/camera --save 
    npm install ng2-img-cropper --save 
    
    生成服务
    ionic g provider photo
    

    先生成一个服务,稍后我们将使用它来处理与 Camera plugin 的交互的服务。

    配置

    编辑文件 src/app/app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';
    
    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    import { PhotoProvider } from '../providers/photo/photo';
    import { Camera } from '@ionic-native/camera';
    import { ImageCropperModule } from "ng2-img-cropper/index";
    
    @NgModule({
      declarations: [
        MyApp,
        HomePage
      ],
      imports: [
        BrowserModule,
        ImageCropperModule,
        IonicModule.forRoot(MyApp)
      ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp,
        HomePage
      ],
      providers: [
        StatusBar,
        SplashScreen,
        Camera,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        PhotoProvider
      ]
    })
    export class AppModule {}
    
    实现具体的服务

    编辑文件 src/providers/photo/photo.ts,实现一个单一的方法 - selectImage - 用于处理设备 photolibrary 的打开,选择所需的图片并将其作为 base64 编码字符串返回:

    import { Injectable } from '@angular/core';
    import { Camera, CameraOptions } from '@ionic-native/camera';
    
    @Injectable()
    export class PhotoProvider {
    
      constructor(private _CAMERA: Camera) { }
    
      selectImage() {
        return new Promise(resolve => {
          let cameraOptions: CameraOptions = {
            sourceType: this._CAMERA.PictureSourceType.PHOTOLIBRARY,
            destinationType: this._CAMERA.DestinationType.DATA_URL,
            quality: 100,
            targetWidth: 320,
            targetHeight: 240,
            encodingType: this._CAMERA.EncodingType.JPEG,
            correctOrientation: true
          };
          this._CAMERA.getPicture(cameraOptions).then(data => {
            let cameraImage = "data:image/jpeg;base64," + data;
            resolve(cameraImage);
          })
        });
      }
    
    }
    
    Home

    src/pages/home/home.ts:

    import { PhotoProvider } from './../../providers/photo/photo';
    import { Component, ViewChild } from '@angular/core';
    import { ImageCropperComponent, CropperSettings, Bounds } from 'ng2-img-cropper';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      @ViewChild('cropper') ImageCropper: ImageCropperComponent;
    
      data: any;
      cropperSettings: CropperSettings;
      croppedWidth: number;
      croppedHeight: number;
    
      constructor(private _PHOTO: PhotoProvider) {
        this.cropperSettings = new CropperSettings();
    
        // Hide the default file input for image selection (we'll be using the Camera plugin instead)
        this.cropperSettings.noFileInput = true;
    
        // Create a new cropped image object when the cropping tool is resized
        this.cropperSettings.cropOnResize = true;
    
        // We want to convert the file type for a cropped image to a JPEG format
        this.cropperSettings.fileType = 'image/jpeg';
    
        this.cropperSettings.rounded = true;
    
        // We want to be able to adjust the size of the cropping tool by dragging from any corner in any direction
        // Cannot set keepAspect to false on rounded cropper
        this.cropperSettings.keepAspect = true;
    
        // Create an object to store image related cropping data
        this.data = {};
      }
    
      selectImage() {
        this._PHOTO.selectImage()
          .then((data: any) => {
            // Create an Image object, assign retrieved base64 image from the device photo library
            let image: any = new Image();
            image.src = data;
    
            // Assign the Image object to the ImageCropper component
            this.ImageCropper.setImage(image);
          })
          .catch((error: any) => {
            console.dir(error);
          });
      }
    
      cropped(bounds: Bounds) {
        this.croppedHeight = bounds.bottom - bounds.top;
        this.croppedWidth = bounds.right - bounds.left;
      }
    
    }
    

    src/pages/home/home.html:

    <ion-header>
      <ion-navbar>
        <ion-title>
          Image Cropper
        </ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
      <!-- Select image from device photolibrary -->
      <button ion-button block color="primary" (click)="selectImage()">Select an Image</button>
    
      <!-- Declare image cropper with following aspects:
    
           1. Template reference variable to allow component
              class to 'hook' into the cropper tool in DOM
           2. Set image from the component class's data object
           3. Apply settings from the component class's cropperSettings object
           4. Call the cropped method in the image cropper's onCrop event
       -->
      <img-cropper #cropper [image]="data" [settings]="cropperSettings" (onCrop)="cropped($event)"></img-cropper>
    
      <!-- Display the cropped image -->
      <div *ngIf="data.image" [class.rounded]="cropperSettings.rounded">
        <img [src]="data.image" [width]="croppedWidth" [height]="croppedHeight">
      </div>
    
    </ion-content>
    

    src/pages/home/home.scss:

    .rounded>img {
      border-radius: 100px;
    }
    

    相关文章

      网友评论

        本文标题:Ionic 3 + Angular Image Cropper

        本文链接:https://www.haomeiwen.com/subject/zodmhftx.html