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
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 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!
I am trying to get the base64 image from the Ionic Cordova camera plugin but it returns me an array with the below details
MediaFile
end: 0
fullPath: "file:/storage/emulated/0/Pictures/1471377463771.jpg"
lastModified: null
lastModifiedDate: 1471377464000
localURL: "cdvfile://localhost/sdcard/Pictures/1471377463771.jpg"
name: "1471377463771.jpg"
size: 3188654
start: 0
type: "image/jpeg"
I tried using the fullPath to convert the image to a base64
$scope.convertImgToBase64URL = function(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
};
But that returns me null. Below is my main call to the camera plugin.
$scope.takePhoto = function () {
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
};
$cordovaCapture.captureImage(options).then(function (imageURI) {
$scope.convertImgToBase64URL(imageURI[0].fullPath, function (base64Img) {
$scope.dataImg = "data:image/jpeg;base64," + base64Img;
$scope.modal.show();
})
}, function (err) {
// An error occurred. Show a message to the user
});
}
Note: If I use Data_URL instead of FILE_URI, it still returns me the same object.
I think you have mixed docs for the capture plugin and the camera plugin.
The capture plugin takes an object specifying how many images to take
var options = { limit: 3 };
and it looks your are passing the params corresponding to the camera plugin instead.
I think you are better off using the camera plugin instead of that capture one if it's just for taking pictures. Your code would end up like this:
var options = {
quality: 75,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 720,
targetHeight: 1280,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation: true
};
cordovaCamera.getPicture(options).then(function (imageData) {
var base64Image = "data:image/jpeg;base64," + imageData;
});
i am new in Ionic, i am trying to get picture and want to store copy or store image into internal storage so i can get back captured image on any view.
I don't know how to store images in internal Storage.
I have read this.
this is Helpful but not solving my issue.
My Controller is here.
Help me in this.
Controller
/**** tab Camera Controller ***/
.controller('tabCameraCtrl', function($scope, $state, $cordovaCamera) {
/**********function to Open Camera *********/
$scope.openCamera = function() {
document.addEventListener("deviceready", function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
// allowEdit: true,
//encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
//popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
// correctOrientation: true
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
$scope.lastPhoto = imageURI;
window.localStorage.setItem('image',JSON.stringify(imageURI));
console.log('success')
console.log('Image Address');
console.log(imageURI);
}, function(err) {
// error
console.log(err)
});
}, false);
}
Help me to solve this problem.
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.