I'm using the cordova camera plugin (I have fetched the latest version from their github) and it is working great on iOS, but it does nothing on Android (Emulator). I'm using Ionic 1. It does open the Camera and all these things, but after I press "Save", nothing else happens.
I know I can't use the camera, so I choose pictures form camera roll. But it seems the getPicture method is never called
Here is the code:
var index = btnIndex;
var source = -1;
if(index == 1){
//choose from album
if(ionic.Platform.isIOS()){
source = Camera.PictureSourceType.PHOTOLIBRARY;
}else{
source = Camera.PictureSourceType.SAVEDPHOTOALBUM;
}
}else if(index == 2){
//take new picture
source = Camera.PictureSourceType.CAMERA;
}
if(source > -1) {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: source,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 320,
targetHeight: 320,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation: true
};
$cordovaCamera.getPicture(options).then(function (imageURI) {
console.log("send file to server");
var imgTag = document.getElementById("myImage");
alert("imageURI: " + imageURI);
var url = SERVER.url + "upload.php";
var opt = new FileUploadOptions();
opt.fileName = $scope.currentUser.clientID + ".jpg";
$cordovaFileTransfer.upload(url, imageURI, opt)
.then(function(result) {
imgTag.src = $scope.currentUser.clientID + ".jpg?" + new Date().getTime(); //time is used to refresh the image
}, function(err) {
alert("Ein Fehler ist aufgetreten: " + JSON.stringify(err));
}, function (progress) {
console.log("progress: " + progress);
});
}), function(error){
alert("ERROR: " + JSON.stringify(error));
};
$cordovaCamera.cleanup();
}
Related
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 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.
I want to use camera plugin cordova 3.4. I need two options. First it can take a photo with camera and Second i can select photo in gallery.
This is my code that i use only camera
function Photo(id, data, format) {
this.id = id;
this.data = data;
this.format = format || "png";
this.name = function() {
var date = new Date();
return "" + date.getTime() + "_" + this.id + "." + this.format;
};
}
SiteCamera = {
dataWithMimeType: function(data) {
return 'data:image/png;base64,' + data;
},
takePhoto: function(idField, updated) {
SiteCamera.id = idField;
SiteCamera.updated = updated;
navigator.camera.getPicture(SiteCamera.onSuccess, SiteCamera.onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG
});
},
onSuccess: function(imageData) {
var imageId = SiteCamera.updated ? "update_" + SiteCamera.id : SiteCamera.id;
var image = document.getElementById(imageId);
var photo = new Photo(SiteCamera.id, imageData);
image.src = SiteCamera.dataWithMimeType(imageData);
PhotoList.add(photo);
},
onFail: function() {
alert("Failed");
}
};
Who can help me i want function that can allow me to use camera option or select photo in gallery. The code that i show all everyone just only chose. if i use 1st option i can use this option only but i need both but i don't know how to do it.
var destinationType = navigator.camera.DestinationType;
var source = navigator.camera.PictureSourceType.PHOTOLIBRARY;
navigator.camera.getPicture(function (imageURI) {
/*Success callback*/
},
function (e) {
/*Fail callback*/
},
{
quality: 100,
destinationType: destinationType.FILE_URI,
sourceType: source
});
You can get image from Camera, Photo Library and Album, to do that just change the source type.
source = navigator.camera.PictureSourceType.PHOTOLIBRARY; //From PhotoLibrary
source = navigator.camera.PictureSourceType.SAVEDPHOTOALBUM; //From Album
source = navigator.camera.PictureSourceType.CAMERA; //From Camera(Default)
I am developing hybrid using phonegap 3.3. I am using camera plugin to capture image and store into photo album which working fine. Later, I have to read image file from the device storage.
I am using the following code.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, failFS);
function gotFS(fileSystem){
fileSystem.root.getFile(imageData, {create: true}, gotFileEntry, fail);
}
function gotFileEntry(){
fileEntry.file(gotFile,fail);
}
function gotFile(file){
alert(file.getParent().fullPath);
}
I am getting error in the first line. It is giving
FileError.ENCODING_ERR
I am not sure what I am doing wrong here. After, I have to move to another directory with new name. Could anyone help me to fix.
I am using camera plugin for capture images and file plugin to read files and directory.
--Sridhar
You can try with below code to capture and copy image
var pictureSource;
var destinationType;
var FileFolder = "";
var FileName = "";
var obj_imageCapture = {
capturePicture:function(imgFolder,imgName)
{
var image = imgFolder + imgName;
FileFolder = imgFolder;
FileName = imgName;
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(obj_imageCapture.onPhotoDataSuccess1, obj_imageCapture.onFail, {quality: 50, destinationType: destinationType.FILE_URI , saveToPhotoAlbum: true });
},
onPhotoDataSuccess1:function(imageData){
obj_imageCapture.createFileEntry(imageData);
},
createFileEntry:function(imageURI) {
window.resolveLocalFileSystemURI(imageURI, obj_imageCapture.copyPhoto, obj_imageCapture.onFFail);
},
copyPhoto:function(fileEntry) {
try
{
var ext = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('.'));
var imageN = "";
if(FileName.indexOf('.') > 0)
{
imageN = FileName.substr(0,FileName.lastIndexOf('.')) + ext;
}
else
{
imageN = FileName + ext;
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(FileFolder, {create: true, exclusive: false}, function(dir) {
fileEntry.copyTo(dir, imageN, obj_imageCapture.onCopySuccess, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}
catch(ex)
{
alert(ex.message);
}
},
onCopySuccess:function(entry) {
var smallimage = document.getElementById("myimage");
smallimage.style.display = "block";
smallimage.src = entry.fullPath + "?rand=" + Math.random();
},
onFFail:function(message)
{
alert("Error in photo : " + message.message);
}
};
Above code might helpful to you