I am relatively new to Ionic 2, Cordova & mobile. I followed a sample app to build a simple camera app. It is very similar to the code in a couple of other questions. Running on my android phone, the camera takes the picture but no image is displayed. The "takePicture fired" log entry displays but no further log entries. Is there something I am missing like a permission issue? Can't understand why I am not even seeing a log entry.
Relevant code:
mypage.html
<button ion-button block color="primary" (click)="takePicture()">Take Picture</button>
...
<img [src]="base64Image" *ngIf="base64Image" />
mypage.ts
export class MyPage {
public base64Image: string;
constructor(public navCtrl: NavController) {
}
takePicture() {
console.log("takePicture fired.");
Camera.getPicture({
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 1000,
targetHeight: 1000
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
if (this.base64Image) {
console.log("base64Image = " + this.base64Image);
}
else {
console.log("base64Image = NULL");
}
}, (err) => {
console.log("An error occurred.");
console.error(err);
});
});
Step 1: In your class.ts
import { Camera } from 'ionic-native';
Step 2: HTML
<img [src]="base64Image" *ngIf="base64Image" (click)="captureImage()"/>
Step 3:
captureImage(){
Camera.getPicture({
quality: 100,
saveToPhotoAlbum: true,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
correctOrientation: false
})
.then((result) => {
this.base64Image = result;
console.log('Image URI: ' + this.base64Image);
}, (error) => {
console.log("ERROR -> " + JSON.stringify(error));
});
}
It's working fine...
Cheers!
Related
I have developed an android application using Ionic4. I am facing some issues with Ionic Native Camera plugin. The following is my code. The issues that i am facing is given below. The version if camera plugin i am using is "#ionic-native/camera": "^5.3.0",.
Issues
Gallery is not opening
Captured image is not returning.
Application crashes after taking picture
html
<img [src]="studentImage!==null ? studentImage: 'assets/icon/ic_avatar.png'" class="add-picture" (click)="addImage()">
.ts
public addImage() {
this.genericServices.presentActionSheet(this.openGallery, this.openCamera);
}
private openCamera = () => {
this.studentImage = this.genericServices.selectPicture('camera');
console.log('Captured Image:=>' + this.studentImage);
}
private openGallery() {
this.studentImage = this.genericServices.selectPicture('gallery');
}
service
public async selectPicture(source) {
let base64Image = null;
const cameraOptions: CameraOptions = {
quality: 75,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.PNG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: source === 'camera' ? this.camera.PictureSourceType.CAMERA : this.camera.PictureSourceType.PHOTOLIBRARY,
correctOrientation: true
};
await this.camera.getPicture(cameraOptions).then((imageData) => {
console.log('Returned Image=>' + base64Image);
return base64Image = 'data:image/jpeg;base64,' + imageData;
}).catch(() => {
});
}
Hard to say what your problem is. I would probably write the code slightly different, like this:
async selectImage() {
const actionSheet = await this.actionCtrl.create({
header: "Select Image source",
buttons: [{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
}
And then in the takePicture() method decide what destinationType should be, default is FILE_URI (1).
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 80,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true,
destinationType: 1,
targetWidth: 1240,
targetHeight: 768,
};
this.camera.getPicture(options)
.then((imageData) => {
// do something with the imageData, should be able to bind it to a variable and
// show it in your html file. You might need to fix file path,
// remember to import private win: any = window, and use it like this.
this.imagePreview = this.win.Ionic.WebView.convertFileSrc(imageData);
}).catch((err) => {
console.warn("takePicture Error: " + err);
});
}
This should work fine... i just tested it. But as i said, there could be several things wrong with your setup. Hope it helps in one way or another... otherwise create a fiddle, and i will gladly look at the code for you.
i am trying ion native camera api , thats takin picture as the camera shows up and i can click an image but tha image is not shoing up
i am using android oreo , ionic 3 and latest cordova and running app on a real device
<-- file home.html-->`
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button round (click)="eventofClick()">Round Button</button>
<p><img src="{{image}}" /> </p>
{{image}}
</ion-content>
<--home.ts-- ------------------------------------------------------>
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
image: any;
constructor(public navCtrl: NavController, public camera: Camera) {
console.log("constructor");
}
eventofClick() {
console.log("called");
console.log('inside');
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
}
i want after taking picture i want to show it along
what i am getting as output is
and at console i am getting 1549019043619.jpg:1 GET unsafe:data:image/jpeg;base64,file:///storage/emulated/0/Android/data/com.catalyst.android.safra/cache/1549019043619.jpg 404 (Not Found)
Try it, this will return you an FILE_URI of your image. If you are uploading image to the server try to show images from your server after uploading. or You can show it directly with base 64. For Base64 you have to change destinationType: this.camera.DestinationType.FILE_URI to destinationType: this.camera.DestinationType.DATA_URL in CameraOptions.
upload Image and Show it.
takePhoto(){
const options: CameraOptions = {
quality: 80,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
console.log(imageData);
this.imageUpload(imageData) / pass your URL in upload function
}, (err) => {
// Handle error
});
}
imageUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'image',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'Server_URL', options)
.then((data) => {
let res = JSON.parse(data.response);
if (res.success == true) {
//server will return you image name Push that name into an array and show it on your View
}
}, (err) => {
console.log(err);
});
}
It's an ionic app with $cordovaImagePicker and $cordovaCamera functions in the same controller and both called from the same reservation.html
This is the controller definition:
.controller('AppCtrl', ['$scope', '$timeout', '$ionicModal', '$localStorage', '$cordovaCamera', '$ionicPlatform', '$cordovaImagePicker', function($scope, $timeout, $ionicModal, $localStorage, $cordovaCamera, $ionicPlatform, $cordovaImagePicker){
I installed $cordovaImagePicker using ionic plugin add cordova-plugin-imagepicker and $cordovaCamera using ionic plugin add cordova-plugin-camera
This is the controller code:
$ionicPlatform.ready(function() {
var options1 = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$scope.takePicture = function() {
$cordovaCamera.getPicture(options1).then(function(imageData) {
$scope.registration.imgSrc = "data:image/jpeg;base64," + imageData;
}, function(err) {
console.log(err);
});
$scope.registerform.show();
};
var options2 = {
maximumImagesCount: 1,
width: 800,
height: 800,
quality: 80
};
$scope.getPicture = function() {
$cordovaImagePicker.getPictures(options2).then(function (results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
$scope.registration.imgSrc = results[i];
}
}, function(error) {
// error getting photos
console.log(error);
});
};
});
}])
I'm running the app on an android 5 phone.
The takePicture function works perfectly.
The getPicture function does not work.
The devTools console shows:
TypeError: Cannot read property 'getPictures' of undefined
at Object.getPictures (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:4420:28)
at Scope.$scope.getPicture (file:///android_asset/www/js/controllers.js:132:37)
at fn (eval at <anonymous> (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:26457:15), <anonymous>:4:221)
at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62386:9
at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29158:28)
at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:29257:23)
at HTMLButtonElement.<anonymous> (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:62385:13)
at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16583:21)
at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2948:7)
at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2937:3)
The error seems to be saying that getPictures is in the scope of Scope.$scope.getPicture but that's not how the code is organised.
I've tried uninstalling and reinstalling $cordovaImagePicker but no change.
After hours of searching for an answer I found this link
https://github.com/ratkop/-cordova-imagePickerEx/issues/8
and reinstalled imagePicker with this :
ionic plugin add https://github.com/b-alidra/-cordova-imagePickerEx.git --save
and it now works without any errors.
I have an app to take photos and upload them when the user synchronises their app. However, it keeps giving me errors after I take the photo and doesnt save it at all to phone.
Here is my code:
(function () {
'use strict';
var serviceId = 'camera';
angular.module('app').service(serviceId, ['$cordovaCamera', '$cordovaFile', '$q', function ($cordovaCamera, $cordovaFile, $q) {
this.takePhoto = function () {
if (window.Camera) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 800,
targetHeight: 800,
saveToPhotoAlbum: true,
correctOrientation: true
};
return $cordovaCamera.getPicture(options).then(function (imageData) {
console.log("Photo Success: " + imageData);
return imageData;
}, function (err) {
console.error("Error taking photo: " + JSON.stringify(err));
throw err;
});
} else {
var deferred = $q.defer();
deferred.resolve("/img/sunrise.jpg");
return deferred.promise;
}
}
}]);
})();
What am I doing wrong here?
First make sure that you include the Camera and File plugins in your project.If not please add this two plugins,
cordova plugin add org.apache.cordova.camera
and
cordova plugin add org.apache.cordova.file
I have made small example for you.Here I am using Ionic’s ngCordova to implement the Camera functionality,.
Conroller
$scope.photoSave = function() {
if (window.cordova) {
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
cameraDirection: 1,
saveToPhotoAlbum: true
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
$scope.imgURI = imagePath;
//Grab the file name of the photo in the temporary directory
var currentName = imagePath.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
//Move the file to permanent storage
$cordovaFile.moveFile(cordova.file.tempDirectory, currentName, cordova.file.dataDirectory, newFileName).then(function(success) {
//success.nativeURL will contain the path to the photo in permanent storage, do whatever you wish with it, e.g:
//createPhoto(success.nativeURL);
}, function(error) {
//an error occured
});
}, function(error) {
//An error occured
});
}
};
HTML
<ion-view>
<ion-content>
<button ng-click="photoSave()">Capture</button>
</ion-content>
</ion-view>
Refer
Now, I have a problem with uploading some images on the server. My code works perfectly on iOS devices, but when I'm trying to upload on Android, it just doesn't do anything. Before the filetransfer, I'm trying to alert the ImageURI, but it's not happening as well.
I'm using PhoneGap Build with Phonegap version 3.4.0 and Sencha Touch 2.3. In the config.xml I use the core phonegap camera plugin: <gap:plugin name="org.apache.cordova.camera" />.
My fileupload script looks like this:
Ext.define('my_app.controller.Fileupload', {
extend: 'Ext.app.Controller',
requires: [
'Ext.MessageBox'
],
config: {
refs: {
fileupload: '#fileupload',
getLibraryImage: 'button[action=getLibraryImage]',
getCameraImage: 'button[action=getCameraImage]'
},
control: {
getLibraryImage: {
tap: 'getLibraryImage'
},
getCameraImage: {
tap: 'getCameraImage'
}
}
},
getLibraryImage: function() {
navigator.camera.getPicture(this.fileupload, onFail, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
targetWidth: 800,
targetHeight: 800
});
function onFail(message) {
alert('Failed because: ' + message);
}
},
getCameraImage: function() {
navigator.camera.getPicture(this.fileupload, onFail, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
quality: 100,
allowEdit: true,
targetWidth: 800,
targetHeight: 800
});
function onFail(message) {
alert('Failed because: ' + message);
}
},
fileupload: function(imageURI) {
alert(imageURI);
Ext.Viewport.setMasked({
xtype: 'loadmask',
message: Loc.t('LOADMASK.FILEUPLOAD'),
styleHtmlContent: true,
indicator: true
});
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
// if (Ext.os.is('Android')) {
// options.chunkedMode = true;
// }
var user = JSON.parse(localStorage.getItem('user'));
var user_id = user.id;
var username = user.username;
var params = new Object();
params.user_id = user_id;
params.username = username;
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("my_upload_uri"), win, fail, options);
function win(response) {
if (Ext.JSON.decode(response.response).error) {
Ext.Viewport.setMasked(false);
Ext.Msg.alert('my_app', Ext.JSON.decode(response.response).error);
} else {
my_app.app.getController('Basic').ProfileImages();
Ext.Msg.alert('my_app', Ext.JSON.decode(response.response).success);
}
}
function fail(error) {
Ext.Viewport.setMasked(false);
alert("An error has occurred: Code = " + error.code);
}
}
});
If anyone can see the problem, I'd really appreciate the help! Thanks in advance.
My problem solved by upgrading to PhoneGap version 3.6.3.