A few days ago a reader asked me an interesting question: How can you select more than one image at a time in a PhoneGap/Cordova application? I did a bit of digging and came up with three different options for handling this. There are probably more, and if you would like to share how you've done it, please add a comment below.
Option One - Camera API
The Camera API only lets you select one image at a time, so it may seem like it isn't a viable solution, but if your code simply keeps track of a list of selections, it may be an option. The user would need to click some button one time for each image they want to use, but depending on your use-case, that may be ok. For example, when I post a picture to Facebook, even though I can post multiple images, I can't honestly remember the last time I did. If Facebook only let me select one existing picture at a time, it wouldn't bother me at all, and that may work fine for your application too.
As an example of this, I created a simple Ionic application that lets you select an image. Every time you select an image, it gets added to a list that is rendered on screen. Here is the controller code I used to handle this:
angular.module('appControllers', [])
.controller('HomeCtrl', ['$scope', '$rootScope', '$cordovaCamera', function($scope, $rootScope, $cordovaCamera) {
$scope.ready = false;
$scope.images = [];
$rootScope.$watch('appReady.status', function() {
console.log('watch fired '+$rootScope.appReady.status);
if($rootScope.appReady.status) $scope.ready = true;
});
$scope.selImages = function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
targetWidth: 200,
targetHeight: 200
};
$cordovaCamera.getPicture(options).then(function(imageUri) {
console.log('img', imageUri);
$scope.images.push(imageUri);
}, function(err) {
// error
});
};
}])
Here is an awesome animated gif of this in action:
Obviously this would be tied to a form process of some sort. You would use the array of images as values with the FileTransfer plugin to send them to your server.
You can view the full source code for this version here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/multiimageselect/multiimageselect1.
Option Two - Media-Capture API
Another option to consider would be the media capture plugin. I don't use this terribly often and I tend to forget that it supports camera images as well. With this plugin, you can request multiple camera images. However, it does not support existing pictures - the user must take new pictures. Also, the user experience is pretty horrible. As I said, I don't use this terribly often and in my testing it wasn't obvious how you stopped the picture taking process. I had to click the device's back button (I only tested this one on Android) to get out of the picture taking cycle and on more than one occasion I accidentally closed the app.
So as I said, this is probably not what I'd use - but it is an option. Here's the controller code updated to make use of that plugin:
angular.module('appControllers', [])
.controller('HomeCtrl', ['$scope', '$rootScope', '$cordovaCapture', function($scope, $rootScope, $cordovaCapture) {
$scope.ready = false;
$scope.images = [];
$rootScope.$watch('appReady.status', function() {
console.log('watch fired '+$rootScope.appReady.status);
if($rootScope.appReady.status) $scope.ready = true;
});
$scope.selImages = function() {
var options = {
limit: 10
};
$cordovaCapture.captureImage(options).then(function(results) {
for (var i = 0; i < results.length; i++) {
$scope.images.push(results[i].fullPath);
}
if(!$scope.$$phase) {
$scope.$apply();
}
}, function(err) {
console.log('err');
console.log(err);
// error
});
};
}])
You can view this version here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/multiimageselect/multiimageselect3
Option Three - cordova-imagePicker
For the final - and probably best - option there is the cordova-imagePicker plugin. This plugin does pretty much exactly what the reader wanted - letting you select multiple images. It has an incredibly simple API allowing for a maximum number of pictures and automatic resizing/quality changes too. Here's how the code works with the defaults:
angular.module('appControllers', [])
.controller('HomeCtrl', ['$scope', '$rootScope', '$cordovaCamera', function($scope, $rootScope, $cordovaCamera) {
$scope.ready = false;
$scope.images = [];
$rootScope.$watch('appReady.status', function() {
console.log('watch fired '+$rootScope.appReady.status);
if($rootScope.appReady.status) $scope.ready = true;
});
$scope.selImages = function() {
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
$scope.images.push(results[i]);
}
if(!$scope.$$phase) {
$scope.$apply();
}
}, function (error) {
console.log('Error: ' + error);
}
);
};
}])
And here it is in action:
Honestly, this seems like the best option. You can see the full source code for this version here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/multiimageselect/multiimageselect2
(As a quick aside, yes, the numbers at the end of each folder don't match the order I did here. The media-capture example is multiimageselect3 and the nicer multi select plugin one is folder 2. Sorry if that's confusing - I just built them in a different order than how I wrote them up.)
As always - I'm curious about how people may have solved this problem in their own PhoneGap/Cordova projects. Please share your ideas below!
Archived Comments
Thank you Raymond !!! I was just waiting for this. Kudos
Very useful, thanks !!
it doesn't work with me. he can't read from content://media....
if the path is 'http://..' it work. what I need do to fix it.
this is my code:
$scope.allImages = [];
function UploadPicture(imageURI) {
$scope.allImages.splice($scope.allImages.length, 0, imageURI);
$scope.$apply();
}
$scope.FindPicture = function () {
navigator.camera.getPicture(UploadPicture, function(imageData) {
alert('get picture failed');
},{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
and in page index.htm:
a class="item item-list-detail">
<ion-scroll direction="x">
<img ng-repeat="image in allImages" ng-src="{{image}}" ng-click="showImages($index)" class="image-list-thumb"/>
</ion-scroll>
can any one help me please.
How doesn't it work?
yes if I want to choose an image from my android phone doesn't work it work only if I take picture directly from my camera. I think it can't read from content //media/external/images/media.
if I choose an image from internet he take it only from the gallery doesn't work.
Um, I'm having a hard time understanding your English. What version of my app did you try?
yes my English not good.
I tried this one "Option Two – Media-Capture API"
And how doesn't it work? It doesn't render in the page?
How can I upload Multiple selected images to server?
You could use the FileTransfer plugin, but it does one at a time. You could also use XHR2.
imagePicker is good but it doesn't support videos.
Hi i am wondering do i have to use Angular js for it? I see that the lib has all the angular js files, but the index just has the ionic referenced. And i just take the folder as it is, the "Multipleimageselect2" folder and packaged that and tried to run it, and clicked the select images, and it doesnt open the gallery.
AngularJS is not required - it is just what I used for my demo. You can't take the code as is - you would need to use Ionic for it. Well, I mean my code. You can use the technique of course outside of Ionic.
This is just what I want , thanks you so much Raymond!
How can I send multiple images selected at same time? Do file transfer support sending multiple images at same time? Is there any other solution to send images except using for loop?
I have form which have some input data fields and images to select which further on click sends data to server. Currently what I am doing is sending form data(using option parameter in file transfer plugin of cordova) every-time with each image and filtering data on server side(prevent adding duplicates).
What will be the best way to achieve above functionality? Thanks
The FileTransfer object only supports one per instance, but you could do N instances and wait for them all to complete. Another option is to use XHR2 which lets you do file uploads via JavaScript too. That isn't a Cordova thing, but a "modern browser" thing. It would let you make one Form post with N uploads.
I can't make any promises, but I've added this idea to my queue of stuff to write.
Hi Raymond, I tried the above code samples for my project.. especially option 3.. but it seems there is problem in getting the picture from photo library..
Below is the part of the program which causing the issue..
pls kindly help me to resolve this issue..
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
var ft = new FileTransfer();
ft.upload(results[i], encodeURI("http://192.168.8.7:80/mShare_fileupload/upload.php"), null, null, options);
console.log('Image URI: ' + results[i]);
$scope.images.push(results[i]);
}
if (!$scope.$$phase) {
$scope.$apply();
}
}, function(error) {
alert("error");
console.log('Error: ' + error);
}, {
maximumImagesCount: 2,
quality: 50,
width: 400,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}
);
You didn't say what your issue was. What I mean is, you said you got an error, but not what the error was.
Hi Raymond,
I have tried to check the above option 3 code to select multiple images at a time by using phonegap.. but i couldn't able to access the photo library by clicking "Select Images" on android device.. Whether your image picker code would support only for ios platform.. ?? Because in all your demo, u had tested only on iOS Simulators.. Could we able to perform the same process on phonegap to support for both ios and android devices..?
Thanks..
So it failed to let you select pictures? If so, you should file bug report with the plugin author to see if they know what it is up. It just worked for me, but as you said, I used iOS.
Great tuts Ray! This really comes in handy. Thanks
You are most welcome.
Hi Raymond, when I use cordova camera plugin I'm getting the file_uri which is different from the file_uri which i was getting from the imagePicker plugin..Due to this different uri I cant able to extract the EXIF data from the URI of imagePicker. Can u plz help me with this.
I don't know how your getting EXIF data now, but it sounds like an issue you should raise with the plugin author.
multipleimageselect2 does not working... no any gallary open. anubody can solve this?
You should reach out to the plugin author directly.
i also have this same type of error. i cant select multiple image at a time but i cant.
Hello raymond, i am not selecting multiple image selection using cordova. i tried multiimageselector2 demo but it crashes every time.In ios, it performs very well. Is anything solution for this?
You need to reach out to the plugin author and report the issue you are seeing.
i dont know plugin author contact details. if u have then please give me. Its too urgent for me.
I linked to the repo in the blog entry.
Hi thanks for your tutorial. Is very helpfull.
With android when I try to open the album the app crash and its close its self.
This bug is happend you too?
I normally test in iOS only - do you see anything in the logs?
Yes. I saw a log with logcat and I submitted new issue on github plugin. You can see the log of the error on github here: https://goo.gl/6tfbWM
Can I ask you to could you try a short test with an Android and check if the bug and the crash happend you too?
My only doubt and maybe that could be my application and not the plugin the cause of crash....
Thank you ray!
So when I try this on Android, window.imagePicker is undefined. I'm not sure why. I've got the platform added for sure. I can see the bits in there. I'd check with the plugin author since its possible they didn't handle the code right for Android.
As an aside, window.plugins.ImagePicker exists - so changing to that would probably fix it for now - at least on Android.
Hi Raymond, I am getting problem with this plugin in android. My application is getting crashed when I am submitting multiple images in android phone. The App is based on phonegap..Could you please help me on this??
If you are sure the plugin is causing it, then your first course of action is to file a bug report on the plugin's github repo. They would be best suited to help you correct it, right?
Hi Raymond , it works great on android but i am facing a problem when i try to upload them , is there any thing you can recommend me to do
What do you see when you remote debug?
Nice tutorial Raymond... but when I use image picker for multiple selection it doesn't show photo library but just a temporary directory with all photos and not album view.. any work around for this?? On android i mean. I googled a lot but not finding any proper solution for this. Thank you
From what I can see of the plugin documentation (the link I had above is dead now, use this: https://www.npmjs.com/packa... this is documented. I'd suggest reaching out to the author and asking if something can be changed about that behavior.
Heyy Raymond , It works fine in browser , But I could not build apk file for android device.
Could you please let me know the solution
How does it fail?
https://uploads.disquscdn.c...
Two things. One, you aren't in a proper Cordova project. My code, as is, can't be used as a project. You have to create a new one, then copy the code into www.
Second, Android is a platform, not a plugin, so you would use: cordova platform add android
window.plugins.imagePicker.getPictures(
function(results) {
alert(results.length);
for (i = 0; i < results.length; i++) {
//images.push(results[i]);
alert('Image URI: ' + results[i]);
//uploadPhoto(results[i]);
//console.log('Image URI: ' + results[i]);
}
}, function (error) {
alert('Error: ' + error);
}, {
maximumImagesCount: 8,
width: 800
}
);
After picking up images message shows processing images. After that in for loop no alert is fired.
What does remote debug show you?
Thanks Raymond. It has been solved. I was doing mistake.
how to define camera oreintation in Media-Capture API
please help
Did you check the docs (https://www.npmjs.com/packa... for it?
this page is not found
Take the ) off at the end of the URL.
can you please tell me what should i change in my code
for correctOreintation
this is my code :
$scope.ready = false;
$scope.images = [];
$scope.selImages = function () {
var options =
{
limit : 20,
};
$cordovaCapture.captureImage(options).then(function (results) {
for (var i = 0; i < results.length; i++) {
var sign = "sign" + i;
$scope.images.push(results[i].fullPath);
}
if (!$scope.$$phase) {
$scope.$apply();
}
}, function (err) {
console.log('err');
console.log(err);
});
When you looked up the docs for MediaCapture, did you see anything related to orientation? What did you try?
I looked the docs there is nothing related to orientation , any other way to control orientation?
Not with the plugin - as far as I know. Once you have the image you could use a Canvas element to rotate it. Possibly.
please can you send me any example?
thank you
I don't have any handy - but I'm sure if you Google for it, you'll find one.
ok thanks
hi
Am also try this code fine only.then which plugin I want add in Coredova can u tell that plugin name sir
Anyone help me pls
Which option are you trying?
sir am using camera
sir am using camera plugin. cordova plugin add cordova-plugin-camera,cordova plugin add org.apache.cordova.camera both are am tying sir
can u send plugin name also sir
3rd option and i need to select gallery from multiple image,video,audio at a time how sir can un give any idea and html part allso
Ok so you added the right plugin.
You are asking a lot of questions here at once and honestly I can't understand you. For option 3, I literally linked to the plugin itself. That's the one you install.
Option Three - cordova-imagePicker
here: https://github.com/cfjedima...
ok sir. i need to select gallery from multiple image,video,audio at a time. how sir can you give any idea and html part allso.
Ok... so are you saying you know the plugin to use?
I don't think you can do that.
IF YOU KNOW GIVE SOME IDEA SIR
ya
window.imagePicker is undefined:
solution here
https://github.com/ratkop/-...
thank you!
Hi Raymond,
Is it possible to load all pics (or select all of them) from gallery or image library to my app to do some process for them.
Thanks.
Hmm. If you have read access to the folder, then you could. It is going to be a *big* upload possibly though so I'm not sure I'd recommend it.
Hi Raymond,
cordova-imagePicker is exactly I wanted but, I need this option for windows app. Is there any other option to select multiple images for cordova windows app.
Thanks.
All I can suggest is searching plugins.cordova.io and filter to the Windows platform.
window.imagePicker.getPicture is nice but they don't support the browser platform :-(
Just use <input type="file" multiple="">
That multiple="" should be just multiple. Disqus changed my input.
We needed an option to develop our custom page that displays and selects photo thumbnails. So here's library I wrote that can enumerate and display images from gallery:
https://github.com/terikon/...
hi about the cordova-imagePicker plugin ; after a user selects and returns back the selection disappears. Is there a way to perverse the selection.
Did you check with the plugin docs?
can anyone suggest me how to avoid that keyboard hides input field of the page in cordova android app ...and also how to access camera ... Kindly post your valuable correct answer
For Camera, look at the Camera plugin.
thanks ...for keyboard any suggestions...?
Off the top of my head - no - but there is a keyboard plugin that I *think* helps with this.
hello sir, how to add camera taken picture in file input plugin for preview..?
No idea what you are asking here.
Hi I have getPicture function in two different controllers inside the same ionic app, the problem is that when I use the function of a co-driver works well but when using it in the other driver no longer works. I think the options of the first function I use are kept, there is some kind of break or clean that allows me to use CordovaCamera on two different controllers with different options.
You got me on that. If you can create a simple, reproduceable case, you could file a bug report on the plugin.
Hello Raymond thanks for response, the error I get is "Selection cancelled" I found this:
"I have seen this problem occur under 2 conditions - 1) Low memory 2) Your events are cascaded, and are triggered twice. For instance, you have a onClick on an Icon, inside a div that also has another event trigger like an a-href or another onClick."
but I dont have idea how to fix in ionic
Ok - and as I said (grin) - if you can make a simple demo of this - use it to file a bug report.
I have installed this plugin but if I try to use it, the window.imagePicker is allways undefined...
Where are you testing - emulator or device?
Hi Raymond
I'm using phonegap desktop to test. If I build the app and install it, I can use imagePicker, but if I call the app using phonegap, it's undefined
When you say you "call the app using phonegap", what exactly do you mean?
I started phonegap desktop, put the url in chrome... window.imagePicker is ok, but,
if I call from phonegap on my cellphone, window.imagePicker is undefined... is it normal?
"If I call from phonegap on my cellphone" - are you saying you used the CLI to install the app on your device, or did you open it with a web browser on your device?
I'm using phonegap client on cellphone...
but if I try to call using CLI, the window.imagePicker is undefined..
I built the app and installed it on cellphone, it works fine.
It won't work there as it has a limited set of baked in plugins.
ok Raymond
thank you...
Thanks for the plugin... works perfect on device...
The plugin isn't mine - I just blogged about it. :)
Raymond, could you help me again?
This plugin works fine on android platform, but, running on IOS, when I click to open gallery, the gallery window opens but it's showed only if I roll down the notification bar...
And, after I select the picture and click OK, my page shows the picture only afer I roll notification bar again...
Not to pass the buck, but that sounds strongly like an issue with the plugin, and it should be raised on their bug tracker.
Ok... I'll write it there... thank you
when i use <input type="file" multiple="multiple" name="file[]"/>
i pick picture but the input is empty
Do you get an error in console? Do you use any other code or literally just the input field?
just the input field (my problem is not to upload multiple i have a solution but the problem is to pick multiple picture then upload it)
I'm not clear what you are asking then. Are you asking about how to upload multiple files? If so, I'd look at the FileTransfer plugin. Or look at XHR2 for uploading files.
Hi, how can i share (with Facebook) the picture which i picked. i m using
EddyVerbruggen/SocialSharing-PhoneGap-Plugin.
can you help me ?
thanks
Not really. This blog post isn't about social sharing. I assume you are having a problem of some sort. I'd reach out to the author of the plugin and tell him what went wrong. If nothing went wrong and you haven't started development yet, then you should be reading the docs there to get started.
thanks for the tutorial sir, what if i want to read all image files automatically with out having either of the above three options can you help on this
You would need to use the File System plugin to look at various directories. You can list files and the such. It is NOT easy to use, but doable.
hello sir , how to access all files from device storage folder.
ex. I am trying to make an app to list images or video like photo gallery in android. but only from one folder ??
This really isn't on topic for this post, but look at the file system plugin.
Hi Raymond, for option 3, after you have selected the multiple images, does it mean that the images save into an array ?
Yep.
When I have tested, I got error
"TypeError: Cannot read property 'getPictures' of undefined", how do I do ?
Did you add the plugin properly?
Yes, I did, everythink done. problem solved, the problem come from the permissions..
in older versions of Android (< 6.0), Android apps do list (during the install process) all the required permissions to run it properly, but in the newest versions of Android, the apps will ask you the permissions during runtime
Do you have a version of option 3 that will work with jQuery rather than angular? I've been having the hardest time getting an image picker to work where I can select multiple images and store them in an array. I've been able to figure out the other Cordova Plugins I need for my app but this one has been the thorn in my side.
Can you share what you've done? Don't post the code in here, but rather share it via a Gist perhaps.
I'm using this plugin: https://www.npmjs.com/packa...
I can't seem to get the 'getPictures(success, fail, options)' method to work. It says that the method is created in the window.imagePicker method but it doesn't do anything.
Since I'm using PhoneGap I don't know how to view the error message because it's running from the app on my phone. I do have the plugin added to my config.xml page as:
<plugin name="cordova-plugin-imagepicker" spec="1.3.0" source="nmp"/>
Any help would be greatly appreciated. I'm new to the PhoneGap/Cordova stuff so it's probably something simple I'm missing.
First - to view error messages, you want to use remote debugging. Please Google for that (I've blogged on it too), but it is a way to connect the Chrome, or Safari, debugger to the running app and view console messages, errors, and the like. You need to do that to figure out what's wrong.