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.");
}
});
}
Related
I am implementing direct upload with Shrine, jquery.fileupload and cropper.js
in the add portion I am loading the image from the file upload to modal, define the cropper and show the modal
if (data.files && data.files[0]) {
var reader = new FileReader();
var $preview = $('#preview_avatar');
reader.onload = function(e) {
$preview.attr('src', e.target.result); // insert preview image
$preview.cropper({
dragMode: 'move',
aspectRatio: 1.0 / 1.0,
autoCropArea: 0.65,
data: {width: 270, height: 270}
})
};
reader.readAsDataURL(data.files[0]);
$('#crop_modal').modal('show', {
backdrop: 'static',
keyboard: false
});
}
Then on the modal button click I get the cropped canvas call on it toBlob and submit to S3
$('#crop_button').on('click', function(){
var options = {
extension: data.files[0].name.match(/(\.\w+)?$/)[0], // set extension
_: Date.now() // prevent caching
};
var canvas = $preview.cropper('getCroppedCanvas');
$.getJSON('/images/cache/presign', options).
then(function (result) {
data.formData = result['fields'];
data.url = result['url'];
data.paramName = 'file';
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
var file = new File([blob], 'cropped_file.jpeg');
console.log('file', file);
data.files[0] = file;
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}
});
});
After the upload to S3 is done I am writing to image attributes to hidden field, closing the modal and destroying the cropper
done: function (e, data) {
var image = {
id: data.formData.key.match(/cache\/(.+)/)[1], // we have to remove the prefix part
storage: 'cache',
metadata: {
size: data.files[0].size,
filename: data.files[0].name.match(/[^\/\\]*$/)[0], // IE returns full path
// mime_type: data.files[0].type
mime_type: 'image/jpeg'
}
};
console.log('image', image);
$('.cached-avatar').val(JSON.stringify(image));
$('#crop_modal').modal('hide');
$('#preview_avatar').cropper('destroy');
}
An chrome everything worked fine from the very beginning, but then I figured out the safari has no toBlob functionality.
I found this one:
https://github.com/blueimp/JavaScript-Canvas-to-Blob
And toBlob is not a function error was gone..
Now I can not save the image due to some mime type related issue.
I was able to find out the exact location where it fails on safari but not chrome.
determine_mime_type.rb line 142
on line 139 in the options = {stdin_data: io.read(MAGIC_NUMBER), binmode: true}
the stdin_data is empty after the io.read
Any ideas?
Thank you!
UPDATE
I was able to figure out that the url to the cached image returned by the
$.getJSON('/images/cache/presign', options)
returns empty file when cropped and uploaded from safari.
So as I mentioned in the question safari uploaded empty file once it was cropped by cropper.js.
The problem clearly originated from this block:
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
var file = new File([blob], 'cropped_file.jpeg');
console.log('file', file);
data.files[0] = file;
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}
I found in some comment on one of the articles I read that safari does some thing like "file.toString" which in my case resulted in empty file upload.
I appended the blob directly without creating a file from it first and everything worked fine.
if (canvas.toBlob) {
canvas.toBlob(
function (blob) {
data.files[0] = blob;
data.files[0].name = 'cropped_file.jpeg';
data.files[0].type = 'image/jpeg';
data.originalFiles[0] = data.files[0];
data.submit();
},
'image/jpeg'
);
}
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 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/
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.