I created a factory to get image from gallery on iOS. Now, I'm testing this factory on emulator(simulator) of iOS and it throws an exception. How I haven't any iOS device to test I want know if this factory only works with device or if it's there a problem with this factory. On Android this factory works fine.
factory
var app = angular.module('starter');
app.factory('CameraFactory', ['$q', function($q) {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: 0, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
}
return {
getPicture: function(callback){
var onSuccess = function(imageData) {
window.resolveLocalFileSystemURL(imageData, function(fileEntry) {
if (callback) callback({
success:true,
path: fileEntry.nativeURL,
imageData: imageData
});
});
};
var onFail = function(e) {
console.log("onFail! " + e);
if (callback) callback( {success:false} );
};
navigator.camera.getPicture(onSuccess, onFail, options);
}
}
}]);
Exception
1 706110 error Error: Can't find variable: Camera
http://192.225.162.87:8100/js/factories/CameraFactory.js:7:32
Line 7 has: Camera.DestinationType.FILE_URI
As #FernandoPaiva stated in the comments, The emulator does not support the API you are trying to access as it doesn't actually have a camera. You can see this noted in the documentation I have linked below.
NOTE: The camera API only works on a real device, and not in the emulator.
http://ngcordova.com/docs/plugins/camera/
Related
So I have the following which works real nice as is:
button.addEventListener("click", function(e){
Titanium.Media.showCamera({
success:function(e){
if(e.mediaType === Titanium.Media.MEDIA_TYPE_PHOTO){
var imageView = Titanium.UI.createImageView({
image: e.media,
width: 'auto',
height: 'auto',
top: 50,
zIndex: 1
});
win.add(imageView);
} else {
alert("Only Photos aloud");
}
},
error:function(e){
alert("There was an error");
},
cancel:function(e){
alert("The event was cancelled");
},
allowEditing: true,
saveToPhotoGallery: true,
mediaTypes:[Titanium.Media.MEDIA_TYPE_PHOTO,Titanium.Media.MEDIA_TYPE_VIDEO],
videoQuality:Titanium.Media.QUALITY_HIGH
});
});
saveToPhotoGallery just adds the taken photo to the default gallery in the iOS Photos App.
I need to add the photo to a specific folder in the iOS Photos App though.
Has anyone an idea how I could do this from with Titanium ?
I have been searching the intewebs but have not found anything on how to add a taken photo to a specific folder.
Thank for the help guys
Chris
But, let me specify that the file can be save in the Application Directory only in IOS but in android you can save it in the externalStorage. You can have look at the documentation through the below link :
https://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage
You can easily save the file to your folder using the following code :
if (OS_ANDROID) {
var f12 = Titanium.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory);
} else {
var f12 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
}
var galleryImg = e.media;
var fileToSave = null;
var fileName = 'IMG' + todayDate + "HB" + Ti.App.Properties.getInt('imgCounter') + '.jpg';
if (OS_ANDROID) {
fileToSave = Titanium.Filesystem.getFile(f12.resolve(), fileName);
} else {
fileToSave = Titanium.Filesystem.getFile(f12.resolve(), fileName);
}
fileToSave.write(galleryImg);
If you want to create a subDirectory then use the following code :
var dir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'mysubdir');
dir.createDirectory(); // this creates the directory
But, let me specify that the file can be save in the Application Directory only in IOS but in android you can save it in the externalStorage. You can have look at the documentation through the below link :
https://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage
EDIT
You Could do it this way :
// get the TiBlob
var blob = img_view.toImage();
// try to save the image the image
Ti.Media.saveToPhotoGallery(blob,{
success: function(e){
if (callback == undefined) {
alert('Saved image to gallery');
} else {
callback();
}
},
error: function(e){
alert("Error saving the image");
}
});
Good Luck, Cheers
I used telerik app builder platform to create application. I created download image functionality. This functionality is working on android device, but not on iOS. I don't know why it is not working.
When the user downloads an image using application in android device, then cordova filesystem creates directory and saves image into that directory and image was also shown in gallery. While user performs same action in iOS then it does not create any directory and the image is not shown in gallery. I haven't found where to save this image.
Please give suggestion on how to save downloaded image in iOS gallery.
My code is below
function onDeviceReady() {
var that = this,
App = new downloadApp(),
fileName = "sample.png",
uri = encodeURI("http://www.telerik.com/sfimages/default-source/logos/app_builder.png"),
folderName = "test";
navigator.splashscreen.hide();
App.run(uri, fileName, folderName);
}
downloadApp.prototype = {
run: function (uri, fileName, folderName) {
var that = this,
filePath = "";
document.getElementById("download").addEventListener("click", function () {
that.getFilesystem(
function (fileSystem) {
console.log(fileSystem);
that.getFolder(fileSystem, folderName, function (folder) {
filePath = folder.toURL() + "\/" + fileName;
console.log(filePath);
that.transferFile(uri, filePath)
}, function () {
console.log("failed to get folder");
});
},
function () {
console.log("failed to get filesystem");
}
);
});
},
getFilesystem: function (success, fail) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
},
getFolder: function (fileSystem, folderName, success, fail) {
fileSystem.root.getDirectory(folderName, { create: true, exclusive: false }, success, fail)
},
transferFile: function (uri, filePath) {
var transfer = new FileTransfer();
transfer.download(
uri,
filePath,
function (entry) {
var targetPath = entry.toURL();
},
function (error) {
console.log(error)
}
);
},
Try to download by using https://www.npmjs.com/package/com-cordova-image-save-to-gallery plugin. It will download a picture from a given URL and save it to IOS Photo Gallery.
Cordova plugin add https://github.com/valwinjose007/cordova-image-save-to-gallery.git
How to use:
declare var CordovaImageSaveToGallery: any;
CordovaImageSaveToGallery.downloadFromUrl('https://picsum.photos/200/300',(res)=>{
//download success
},(err)=>{
//error on download
});
I'm building a hybrid app in ionic, which runs over cordova. I use the $cordovaCamera plugin to capture images from the phone, either by selecting from the phone's gallery or by using the camera to take a picture.
I then send that image using Restangular to my server, and when that action finishes, I want to display a status message on the screen.
My problem: All of the above works perfectly on Android. On iOS, it is working only when the image is selected from the gallery, but not when the image is directly captured from the phone. In that case, the image is correctly transferred to the server, the request returns a 201 Created just as it should - but the then() callback function is never entered.
If anyone can explain this behavior, that would be awesome...my second best would be to capture the image on the iPhone, save to gallery, and then attempt to retrieve the last saved image, but I haven't been able to figure out how to yet and I'd rather just get this working.
Update: I've narrowed it down to the Restangular part - if instead of calling the Restangular upload function, I use $http, the callback is triggered as expected and all is good...so that's what I'm going to do, but if anyone can tell me what the problem was I'd be grateful.
Relevant code:
/** cameraService functions **/
//when the user chooses to snap a picture from the camera
takePicture: function(){
var options = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions
};
return $cordovaCamera.getPicture(options).then(
function(imageData) {
return imageData;
},
function(err) {
console.log("error", err);
});
},
//when the user chooses to select image from the gallery
choosePicture: function(){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
};
return $cordovaCamera.getPicture(options).then(
function(imageData) {
return imageData;
},
function(err) {
console.log("error", err);
});
},
uploadPicture: function(imageSource, caption, is_logo){
if (typeof is_logo == 'undefined') is_logo = false;
var upload_object = {
caption: caption,
source: imageSource,
is_logo: is_logo
};
//apiService is my wrapper for Restangular
return apiService.uploadFile(loadingService.getClientUrl('images'), upload_object);
},
/**apiService uploadFile - apparently the problem is here ***/
uploadFile: function(baseElem, object, route, path){
var headers = apiFunctions.setHeaders({'Content-Type': undefined});
//this DOES NOT WORK (on iPhone with image from camera) - request completes but callback not triggered
return Restangular.all(baseElem).customPOST(object, path, route, headers);
//this works fine:
return $http.post('https://api.mysite.dev/v1/clients/'+localStorageService.getValue('client_id')+'/images', JSON.stringify(object), {headers:headers}
);
},
/** controller functions **/
$scope.takePicture = function () {
cameraService.takePicture().then(function (imageData) {
$scope.data.imageSource = imageData;
});
};
$scope.choosePicture = function () {
cameraService.choosePicture().then(function (imageData) {
$scope.data.imageSource = imageData;
});
};
$scope.uploadPicture = function () {
cameraService.uploadPicture($scope.data.imageSource, $scope.data.caption)
.then(function (response) { //this is never entered if image is captured from camera on iPhone
$ionicScrollDelegate.scrollTop();
$scope.data.caption = '';
$scope.data.imageSource = '';
if (response.data.response.is_success.data_value == true) {
$scope.messages.success.push("Photo uploaded successfully");
} else {
$scope.messages.failure.push("Error uploading photo.");
}
});
}
I'm using phonegap 3.3 and when I try to upload the upload the picture to server via file transfer plugin, I'm getting error 3 and http-status 500 on ios 7, on android it's working perfectly with no problem.
my client code:
function onSuccess(imageURI) {
$.mobile.loading('show');
try{
var options = new FileUploadOptions();
options.fileKey='file';
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType='image/jpeg';
var ft = new FileTransfer();
ft.upload(imageURI, path + "/Home/postPicture", win, fail, options);
} catch(err){
$.mobile.loading('hide');
alert(err);
}
}
function win(data) {
var obj = $.parseJSON(data.response);
$("#PictureSource").val(obj.PictureSource);
$.mobile.loading('hide');
}
function fail(error) {
$.mobile.loading('hide');
alert("error " + error.code);
}
function onFail() {
navigator.notification.alert(
'שגיאה לא ידועה...נסה שנית!', // message
alertDismissed, // callback
'שגיאה', // title
'אישור' // buttonName
);
}
function selectInput() {
navigator.notification.confirm(
'בחר את מקור התמונה', // message
onSelect, // callback to invoke
'בחירת מקור', // title
'מצלמה,גלריה, ביטול' // buttonLabels
);
}
function onSelect(input) {
switch(input)
{
case 1:
{
var destinationType = navigator.camera.DestinationType;
var sourceType = navigator.camera.PictureSourceType;
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
//correctOrientation: true,
sourceType: sourceType.CAMERA
});
}
break;
case 2:
{
var destinationType = navigator.camera.DestinationType;
var sourceType = navigator.camera.PictureSourceType;
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: sourceType.PHOTOLIBRARY
});
}
break;
case 3:
alertDismissed();
break;
default:
alertDismissed();
}
}
function alertDismissed() {
// do nothing
}
and my server side in ASP.net MVC 4 is pretty much the same as here (I have chekced it, and it working with no problem on android).
Please help,
Update:
when I'm trying to upload image from gallery it does work on ios, but taking picture and uploading it doesn't work, do you thine is a phonegap/cordova bug? or it's something else?
I have been using the following code to grab a photo and display it in html works great.
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image1');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
{ quality: 50, allowEdit: true, destinationType: navigator.camera.DestinationType.FILE_URI});
};
html later
<img style="width:144px;height:144px;" id="camera_image1" src="nophoto.jpg"/>
However I would like to save the image to the users Library at the same time, any pointer much appreciated.
I have tried using captureImage but this gives me less options like editing and did not place image inline in html.
Thanks again
PhoneGap 1.3
With Phonegap 2.2 you can save the image to the local device.
add "saveToPhotoAlbum : true" to the cameraOptions
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image1');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
}, {
quality: 50,
allowEdit: true,
destinationType: navigator.camera.DestinationType.FILE_URI,
saveToPhotoAlbum : true
});
};
you'll have to change the phonegap code a bit. it wont save the image in the implementation thats there currently.
tell me if you are working on phonegap android. may be able to help u with that.