How would I get a File object from PhoneGap camera.getPicture? - javascript

This is probably simple and covered by some combination of functions in PhoneGap's "Camera" plugin, "File" plugin, or "File-Transfer" plugin. I understand the user can select a file with:
navigator.camera.getPicture(function (fileURI) {
// *** need help here ***
}, function ()
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});
I can also change to destinationType: window.Camera.DestinationType.DATA_URL if that makes a difference.
My goal in the success handler is to get a File object (https://developer.mozilla.org/en-US/docs/Web/API/File).

Something like this should do it.
navigator.camera.getPicture(function (fileURI) {
window.resolveLocalFileSystemURL(fileURI,
function(fileEntry){
alert("got image file entry: " + fileEntry.fullPath);
// fileEntry.file() should return a raw HTML File Object
},
function(){//error}
);
}, function (){
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});

window.resolveLocalFileSystemURI(fileURI, function(fileEntry) { /* your code here */ });

Related

Angular JS Camera plugin base64 string

I am trying to use camera plugin with cordova app in ionic angular.js. My problem is that when i get picture it gives me a url of image not base64 string
I need base64 string.
in 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;
}
}
});
I user code above this returns
file:///storage/emulated/0/Android/data/com.example.app/cache/1313513121.jpg
but I want base64 string because I send it to server to save the image in server
in Controller.js
$scope.AddImage = function () {
var options = {
quality : 75,
targetWidth: 200,
targetHeight: 200,
sourceType: 1
};
Camera.getPicture(options).then(function(imageData) {
alert(imageData);
var item={
image: imageData
}
Pictures.push(item);
$scope.Photos = Pictures;
}, function(err) {
console.log(err);
});
}
I wrote code above. How can I solve this problem
Thanks in advance
Use the destinationType option parameter with value DATA_URL on the [ cameraOptions ].
navigator.camera.getPicture( cameraSuccess, cameraError, [
cameraOptions ] );
The option destinationType: Camera.DestinationType.DATA_URL will allow you to take a photo and retrieve the Base64-encoded image. Default this is set to destinationType: Camera.DestinationType.FILE_URI which will retrieve the image file location.
Below a general code sample which you can use to adapt your existing code.
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Documentation here

Save image to a specific folder using cordova

I am trying to save an image captured using cordova camera plugin to a specific directory for windows 8.1 application. But I am not able to find an exact solution for this. I have gone through many questions and forums, no luck.
Here is a sample code I have tried.
onTakePhoto: function () {
navigator.camera.getPicture(this.onPhotoSuccess, this.onPhotoFail, {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
encodingType: Camera.EncodingType.JPEG,
sourceType: Camera.PictureSourceType.CAMERA,
saveToPhotoAlbum: false
});
},
//Callback function if onTakePhoto action is success.
onPhotoSuccess: function (oImageURI) {
console.log("In Success " + oImageURI);
window.resolveLocalFileSystemURI(oImageURI, this.handlePicSave, this.onPhotoFail);
},
//Callback function if onTakePhoto action fails
onPhotoFail: function (oError) {
console.log("In Fail " + oError);
},
//Handle pic save
handlePicSave: function(oEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSys) {
fileSys.root.getDirectory("MyPhotos", { create: true, exclusive: false }, function (directory) {
oEntry.moveTo(directory, "WO_2.jpg", that.successMove, that.onPhotoFail);
}, that.onPhotoFail);
},
that.onPhotoFail);
},
The above code works fine and saves the image to the app root folder i.e C:\Users\..\AppData\Local\Packages\App_name\LocalState\MyPhotos\WO_2.jpg
But I need to store directly to C drive like.. C:\MyPhotos\WO_2.jpg
I think you should check cordova file plugin, It allows to access differents folders and read / write. I do not use it for camera purposes, but I used it for saving files in diferent projects and works fine.

Ionic error (Camera and File transfer plugin)

I am developing a mobile application and I getting an error when the user try to change the picture profile, the error after do a lot of debugging is not in the camera is in the file transfer function when I try to send the image to the server, there is no error code or message, simply the application stop work, this is the code:
$scope.addImage = function (option) {
var options = {
quality: 75,
targetWidth: 300,
destinationType: Camera.DestinationType.DATA_URL,
targetHeight: 300,
saveToPhotoAlbum: false,
correctOrientation: true
};
if (option == 1) {
options.sourceType = Camera.PictureSourceType.CAMERA;
} else {
options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
}
$cordovaCamera.getPicture(options).then(function (imageData) {
console.log("IMAGE DATA");
console.log(imageData);
//alert("SUCCESS");
$scope.user.image = "data:image/jpeg;base64," + imageData;
console.log(JSON.stringify($scope.user));
$scope.savePicture();
}, function (err) {
alert("ERRROR");
alert(JSON.stringify(err));
// An error occured. Show a message to the user
});
};
$scope.savePicture = function () {
var options = {
fileKey: "avatar",
fileName: "image.jpg",
chunkedMode: false,
mimeType: "image/jpeg",
headers: {
Authorization: "Bearer " + $auth.getToken()
}
};
$cordovaFileTransfer.upload(api.getApi()+"user/updatephoto", $scope.user.image, options).then(function (result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
alert("ERROR: " + JSON.stringify(err));
}, function (progress) {
// constant progress updates
});
};
Thank in advice for your help
you are not calling return appropriately on your functions that return a promise. From a quick review, $scope.savePicture(); should be return $scope.savePicture();
and $cordovaFileTransfer.upload() should also be return $cordovaFileTransfer.upload()
I would start there and see if you start to make some progress.
I had to debug the entire application including the cat log of android and I found the problem.
The problem was that I am using Ionic with crosswalk and the version of FileTransfer that I was using does not support crosswalk.
I fix this problem just installing the last version of file transfer:
cordova-plugin-file-transfer 1.2.1 "File Transfer"

Cordova WP8 resolveLocalFileSystemURL fails

Good day, i have a project on cordova that uses image gallery and camera and stores images in local cache folder.
So i installed:
org.apache.cordova.camera 0.3.1 "Camera"
org.apache.cordova.file 1.3.1 "File"
org.apache.cordova.file-transfer 0.4.6 "File Transfer"
Android and iOS works perfectly, but when it comes to WP8 (Windows Phone 8), following code:
$scope.uploadImageFromPhone = function(isCamera){
console.log('uploadImageFromPhone');
var opt = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: (isCamera) ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,
encodingType: Camera.EncodingType.JPEG
};
function onGetImageSuccess(fileUrl) {
console.log('onGetImageSuccess:\n'+fileUrl);
window.resolveLocalFileSystemURL(fileUrl, resolveSuccess, resolveFails);
}
function onGetImageFail(message) {
//console.log('onGetImageFailed:\n' + JSON.stringify(message));
}
function resolveSuccess (path) {
console.log('resolveSuccess:');
console.log(JSON.stringify(path));
uri = path.nativeURL;
//wp8 returns null as path.nativeURL
/*IE10 specific hack*/
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
uri = path.fullPath;
}
}
function resolveFails(err){
console.log('resolveFails:\n' + JSON.stringify(err));
};
navigator.camera.getPicture(onGetImageSuccess, onGetImageFail, opt);
}
The resolveSuccess function always returns path variable as shown below:
{"isFile":true,"isDirectory":false,"name":"wp_ss_20140923_0001.png","fullPath":"///CapturedImagesCache/wp_ss_20140923_0001.png","filesystem":"<FileSystem: temporary>","nativeURL":null}
Problem is that nativeURL is null.
According to my app, chosen file must be put in application local cache, so i try to download it and store in cache by approaching to fullPath with file-transfer plugin:
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri, // equals to '///CapturedImagesCache/wp_ss_20140923_0001.png'
'wp_ss_20140923_0001.png',
function(entry){
//file processing
console.log('downloaded successfull');
},
function(error){
console.log("download error" + JSON.stringify(error));
},
false,
{}
);
This code always returns me console output:
download error: {"code":2,"source":"///CapturedImagesCache/wp_ss_20140923_0001.png","target":null,"http_status":null,"body":null,"exception":null}
I don't get it, what am i doing wrong here?
P.S: cordova version: '3.6.3-0.2.13'

Valums file uploader plugin shows upload failed message each time

I am using valum file uploader. The js code for initializing plugin is:
function Initializer() {
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/_Image/Upload',
params: {},
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
debug: true,
onSubmit: function (id, fileName) { },
onProgress: function (id, fileName, loaded, total) { },
onComplete: function (id, fileName, responseJSON) { },
onCancel: function (id, fileName) { },
onError: function (id, fileName, xhr) { },
messages: {
typeError: "{file} has invalid extension. Only {extensions} are allowed.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
allowedExtensionsError : "{file} is not allowed.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
showMessage: function (message) {
alert(message);
}
});
}
The file is successfully uploaded on the server but the plugin is showing the file uplode fail message each time.
What's the issue?
You are most likely not returning valid JSON as your server response. The readme clearly states, in many places, that this is required. Please have a look at the readme.

Categories