Ionic-camera
イオン-Cordovaカメラ
Cordovaカメラプラグインは、*ネイティブカメラ*を使用して、写真を撮影したり、画像ギャラリーから画像を取得したりします。
カメラを使用する
コマンドプロンプトでプロジェクトルートフォルダーを開き、次のコマンドでCordovaカメラプラグインをダウンロードしてインストールします。
C:\Users\Username\Desktop\MyApp> cordova plugin add org.apache.cordova.camera
次に、カメラプラグインを使用するためのサービスを作成します。 * AngularJSファクトリー*と、ファクトリーに注入する必要があるオブジェクト $ q を使用します。
services.jsコード
.factory('Camera', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
});
このサービスをアプリで使用するには、依存関係としてコントローラーに注入する必要があります。 CordovaカメラAPIは、 getPicture メソッドを提供します。このメソッドは、ネイティブカメラを使用して写真を撮影するために使用されます。
ネイティブカメラの設定は、 options パラメーターを takePicture 関数に渡すことでさらにカスタマイズできます。 この動作をトリガーするには、上記のコードサンプルをコントローラーにコピーします。 カメラアプリケーションを開き、画像データを含む成功コールバック関数またはエラーメッセージを含むエラーコールバック関数を返します。 また、作成しようとしている機能を呼び出す2つのボタンが必要になり、画面に画像を表示する必要があります。
HTMLコード
<button class = "button" ng-click = "takePicture()">Take Picture</button>
<button class = "button" ng-click = "getPicture()">Open Gallery</button>
<img ng-src = "{{user.picture}}">
コントローラコード
.controller('MyCtrl', function($scope, Camera) {
$scope.takePicture = function (options) {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 1
};
Camera.getPicture(options).then(function(imageData) {
$scope.picture = imageData;;
}, function(err) {
console.log(err);
});
};
})
出力は次のスクリーンショットのようになります。
ギャラリーの画像を使用する場合、変更する必要があるのは、optionsパラメーターの sourceType メソッドのみです。 この変更により、カメラではなくダイアログポップアップが開き、デバイスから必要な画像を選択できるようになります。
次のコードを見ると、 sourceType オプションが 0 に変更されています。 これで、2番目のボタンをタップすると、デバイスからファイルメニューが開きます。
コントローラコード
.controller('MyCtrl', function($scope, Camera) {
$scope.getPicture = function (options) {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 0
};
Camera.getPicture(options).then(function(imageData) {
$scope.picture = imageData;;
}, function(err) {
console.log(err);
});
};
})
出力は次のスクリーンショットのようになります。
撮影した画像を保存すると、画面に表示されます。 好きなようにスタイルを設定できます。
他のいくつかのオプションも使用できます。その一部を次の表に示します。
Parameter | Type | Details |
---|---|---|
quality | Number | The quality of the image, range 0-100 |
destinationType | Number | Format of the image. |
sourceType | Number | Used for setting the source of the picture. |
allowEdit | boolean | Used for allowing editing of the image. |
encodingType | Number | Value 0 will set JPEG, and value 1 will set PNG. |
targetWidth | Number | Used for scaling image width. |
targetHeight | Number | Used for scaling image height. |
mediaType | string | Used for setting the media type. |
cameraDirection | Number | Value 0 will set the back camera, and value 1 will set the front camera. |
popoverOptions | string | IOS-only options that specify popover location in iPad. |
saveToPhotoAlbum | boolean | Used for saving image to photo album. |
correctOrientation | boolean | Used for correcting orientation of the captured images. |