首页 > 解决方案 > ionic v3 原生相机插件在 android 上不起作用

问题描述

使用 ionic cordova 插件在 android 上的打开相机或图库上不起作用

离子:

离子(离子 CLI):4.12.0 离子框架:离子角 3.9.2 @ionic/app-scripts:未安装

科尔多瓦:

科尔多瓦(科尔多瓦 CLI):8.1.2(科尔多瓦-lib@8.1.1)

系统:

NodeJS:v10.15.3 npm:6.9.0 操作系统:Windows 10

takePicture() {
        const options: CameraOptions = {
          quality: 75,
          destinationType: this.camera.DestinationType.NATIVE_URI ,
          encodingType: this.camera.EncodingType.JPEG,
          mediaType: this.camera.MediaType.PICTURE,
          sourceType: this.camera.PictureSourceType.CAMERA,
          allowEdit: true,
          correctOrientation: true,
          targetWidth: 300,
          targetHeight: 300,
          saveToPhotoAlbum: true
        }

         alert("1");
      this.camera.getPicture(options).then(imageData => {
        
          let base64Image = 'data:image/jpeg;base64,' + imageData;
          this.image = base64Image;
          alert("done");
        }, error => {
      //  Utils.showToast( null,JSON.stringify(error));
        });
        
      }

标签: cameraionic3ionic-native

解决方案


你错过了最重要的一步,确保你camera在提供者中引入一个app.module.ts

你应该像这样创建一个 PictureProvider 文件

import { Injectable } from '@angular/core';
import { Defer } from '../../common/Defer';
import { Camera } from '@ionic-native/camera';

export enum PictureSource {
	PhotoLibrary,
	Camera,
	Local,
	Remote,
}

@Injectable()
export class PictureProvider {

	constructor(private camera: Camera, ) {
		console.log('Hello PictureProvider Provider');
	}

	fromCamera(source: PictureSource, options?, ) {
		let mergedOtions = this.getOptions(source, options);
		if (options)
			for (let k in options)
				mergedOtions[k] = options[k];

		let defer = Defer.create();

		navigator['camera'].getPicture(
			imageUri => defer.resolve(imageUri),
			(message: string) => {
				console.log(message);
				defer.reject();
			},
			mergedOtions,
		);

		return defer.promise;
	}

	private getOptions(source, options?) {
		return {
			sourceType: source == PictureSource.PhotoLibrary ? this.camera.PictureSourceType.PHOTOLIBRARY : this.camera.PictureSourceType.CAMERA,
			destinationType: this.camera.DestinationType.NATIVE_URI,
			quality: 50,
			mediaType: this.camera.MediaType.PICTURE,
			allowEdit: options.allowEdit,
			correctOrientation: true,
			targetWidth: options.targetWidth,
			targetHeight: options.targetHeight
		}
	}

}

根据需要执行

this.picture.fromCamera(1, {
        allowEdit: true,
        targetWidth: 256,
        targetHeight: 256,
        destinationType: this.camera.DestinationType.DATA_URL,  //直接返回base64
    }).then(base64Img => {
        this.headImg = this.encodeBase64Img(base64Img);
    }).catch(Defer.NoOP);

推荐阅读