如何在Ionic 2中使用原生智能手机相机?

时间:2016-01-09 16:14:02

标签: cordova mobile camera ionic cordova-plugins

Ionic 1似乎有一些cordova插件允许你这样做。我真的需要逐步了解如何使用Ionic 2进行此操作。似乎没有资源可以在线获取。

谢谢!

3 个答案:

答案 0 :(得分:2)

在项目文件夹中,运行:

$ ionic plugin add cordova-plugin-camera --save

然后您将navigator.camera作为全局提供。

import {Page, Platform, NavParams} from 'ionic/ionic'; import {NgZone} from 'angular2/core';






constructor(platform:Platform, navParams: NavParams, _zone : NgZone) {
this._zone = _zone;
this.platform = platform;
this.images = [];}



takePhoto() {
this.platform.ready().then(() => {
  let options = {
    quality: 80,
    destinationType: Camera.DestinationType.DATA_URL,
    sourceType: Camera.PictureSourceType.CAMERA,
    allowEdit: false,
    encodingType: Camera.EncodingType.JPEG,
    saveToPhotoAlbum: false
  };
  // https://github.com/apache/cordova-plugin-camera#module_camera.getPicture
  navigator.camera.getPicture(
    (data) => {
      let image = "data:image/jpeg;base64," + data;
       this._zone.run(()=> this.images.unshift({
         src: image
       }))
    }, (error) => {
      alert(error);
    }, options
  );
});}

在这里制作了一个演示项目;仅在Android中测试过,请试试。

https://github.com/marcusasplund/ionic2-camera-demo/

答案 1 :(得分:2)

步骤1:通过运行以下命令添加ionic-native:

  

<强> mysql2

步骤2:添加npm install ionic-native --save以添加摄像机图像或从图库中选择图像。

运行以下命令将插件添加到项目中:

  

<强> cordova camera plugin

使用插件的示例代码:

cordova plugin add cordova-plugin-camera

// Returns a image path location of : file:///storage/emulated/0/Android/data/io.ionic.starter/cache/1460010653820.jpg takeNewImage(){ var option = { sourceType:1, quality: 20, destinationType: 0, encodingType: 0 }; Camera.getPicture(option).then((imageData)=>{ this.cameraSuccessCallback(imageData); },(error)=>{ this.cameraErrorCallback(error); }); } // Returns a file URI : content://media/external/images/media/51516 chooseImage(){ var option = { sourceType:0, quality: 20, destinationType: 0, encodingType: 0 }; Camera.getPicture(option).then((imageData)=>{ this.cameraSuccessCallback(imageData); },(error)=>{ this.cameraErrorCallback(error); }); } cameraSuccessCallback(imageData) { console.log("Getting image data as base64 string from camera/Gallery success."); console.log(imageData); var cardImage = document.getElementById("image-preview"); cardImage.src = "data:image/jpeg;base64,"+imageData; } cameraErrorCallback(message) { alert('Loading image failed due to: ' + message); } 是图片的base64字符串值。

参考

  1. cordova-plugin-camera
  2. Ionic2 Forum discussion
  3. Ionic2 official documentation

答案 2 :(得分:1)

安装ionic-native并添加您需要的plugin

Regex nonNumeric = new Regex(@"\D");
var r = nonNumeric.Replace(
    HttpUtility.HtmlDecode("0&shy;12&shy;4 41&shy;481&shy;73"), 
    string.Empty);

然后在你的代码中:

$ npm install ionic-native --save-dev

$ ionic plugin add phonegap-plugin-barcodescanner --save