1.15 ionic3入门——相册

2018-09-29  本文已影响0人  杨啊杨_fb52

(1)安装相册选择插件 image picker

ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="允许App访问你的相册"
npm install --save @ionic-native/image-picker

(2)在app.module.ts中引用声明

import { ImagePicker } from '@ionic-native/image-picker';

在providers中声明ImagePicker
(3)在要使用的页面引用,以及在构造函数中声明

import { ImagePicker,ImagePickerOptions } from '@ionic-native/image-picker';

在构造函数中声明private imagePicker: ImagePicker

  constructor(public navCtrl: NavController, public navParams: NavParams,public actionSheetCtrl: ActionSheetController,private camera: Camera,
    private imagePicker: ImagePicker,) {
      
  }

(4)使用

  pick_img(){
    const options:ImagePickerOptions ={
        maximumImagesCount:9-that.image_num,
      quality:50,
      outputType : 1  //默认为0,返回类型为file_url;为1,返回值为base64-encoded string
    };
    that.imagePicker.getPictures(options).then((results) => {
        for (var i = 0; i < results.length; i++) {
      
       let base64Image = 'data:image/jpeg;base64,' + results[i];
      
        }
      }, (err) => { 
        alert('未进行照片选取~');
        //alert(err);
    });

  }

(5)用这个方法不知道为什么在安卓上就死机了,所以我在安卓上用调用摄像头的方式,通过参数改为相册来实现从相册选取照片的功能,唯一不足之处就是一次性只能选一张照片

 android_pick_img(){
      const options: CameraOptions = {
      quality: 60,                                                   // 相片质量 0 -100
      destinationType: that.camera.DestinationType.DATA_URL,        // DATA_URL 是 base64   FILE_URL 是文件路径
      encodingType: that.camera.EncodingType.JPEG,
      mediaType: that.camera.MediaType.PICTURE,   //有PICTURE VIDEO ALLMEDIA
      saveToPhotoAlbum: true,                                       // 是否保存到相册
      sourceType: that.camera.PictureSourceType.PHOTOLIBRARY ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,

    }

    that.camera.getPicture(options).then((imageData) => {
      console.log('got file: ' + imageData);

       // If it's base64:
       let base64Image = 'data:image/jpeg;base64,' + imageData;

    }, (err) => {
      //alert(err);
      // Handle error
    });

  }
上一篇下一篇

猜你喜欢

热点阅读