Ionic Camera Functionality – Take a Picture or Choose from Library

Author: Ben B. Ben B | 6/24/16

I recently finished an IOS app using the Ionic framework. I really enjoyed the experience. Ionic has tons of time saving features, and it is based on Apache Cordova, so you can use Cordova plugins to make apps that feel quite native.

My project comps required a button that would allow the user to choose a picture from their library or take a picture. As I searched the web for the easiest way to do this, most of the articles talked about using two plugins ( cordova-plugin-camera and cordova-imagePicker). This made me cringe. Wasn’t there a plugin powerful enough to do both? Not only that, but I got down the road a little bit and couldn’t get cordova-imagePicker to work on my project.

Hopefully this article will save you some time. 🙂

Some caveats:

  • I’ve only tested this on IOS, but in theory it should work on Android too.
  • I have the following dependencies in my package.json:
    {
     "dependencies": 
      {
       "ionic": "^1.7.14",
       "cordova": "^6.1.1",
      }
    }
    

Install Cordova Camera Plugin

You need to install the Cordova Camera Plugin (e.g. I’ve installed cordova-plugin-camera@2.2.0)

ionic plugin add cordova-plugin-camera@2.2.0

Using the Ionic CLI is important here (as opposed to the cordova CLI) because the ionic automatically adds the following line to your package.json

{
 "cordovaPlugins": [
  "cordova-plugin-camera@2.2.0",
 ],
}

Make sure your package.json updates. An updated package.json file is helpful because then you can run `ionic state restore` and instantly have the same exact plugins as required by your code. 

Install ngCordova

You can install inCordova with bower:

bower install ngCordova --save

Then include the new file in your index.html file:

<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>

Now you can inject it into Angular:

angular.module('myApp', ['ngCordova'])

See the official ngCordova install directions here.

Start Using The Camera

Here is were the magic happens! Like I mentioned, other articles were saying that you needed both cordova-plugin-camera and cordova-imagePicker, but the latter isn’t necessary.

The most important part of what I’m going to show you is…

$cordovaCamera.getPicture(uploadPhotoOptions).then(takePictureSuccess,takePictureError);

A full list of options (uploadPhotoOptions) can be found at the cordova camera plugin github repo.

The most important option for our purposes is…


uploadPhotoOptions.sourceType = Camera.PictureSourceType.CAMERA;

OR

uploadPhotoOptions.sourceType = Camera.PictureSourceType.PHOTOLIBRARY

It should be pretty self explanitory. Just call $cordovaCamera with the sourceType = Camera.PictureSourceType.PHOTOLIBRARY for photolibrary and Camera.PictureSourceType.CAMERA for camera.

One gotcha…

Camera.PictureSourceType.CAMERA only works on an actual device, unfortunately you can’t test in the Ionic emulator (i.e. `ionic run emulate`).

Full Code Example

I’ve included a full working sample below.

$ionicActionSheet.show({
 buttons: [
  { text: 'Take Photo' },
  { text: 'Choose Photo' },
 ],
 cancelText: 'Cancel',
 titleText: 'Take or Choose a Photo',
 buttonClicked: buttonClicked,
});
function buttonClicked(index){

 var uploadPhotoOptions = {
   quality: 50,
   destinationType: Camera.DestinationType.DATA_URL, //FILE_URI, NATIVE_URI, or DATA_URL. DATA_URL could produce memory issues. 
   sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
   encodingType: Camera.EncodingType.JPEG,
   allowEdit: true,
   targetWidth: 300,
   targetHeight: 300,
   saveToPhotoAlbum: false,
 };

 if (index == 0) { // Take photo
 
   uploadPhotoOptions.sourceType = Camera.PictureSourceType.CAMERA; 
 } else if (index == 1) { //Choose Photo
 
   uploadPhotoOptions.sourceType = Camera.PictureSourceType.PHOTOLIBRARY; 
 }

 $cordovaCamera.getPicture(uploadPhotoOptions).then(takePictureSuccess,takePictureError);
 function takePictureSuccess(success) { 

   vm.userProfile.image = "data:image/jpeg;base64,"+success; //this is how I store the image to firebase
 };
 function takePictureError(error) {
   $ionicPopup.alert({
     title: 'Photo Error',
     template: error,
   });
 };

 return true;
}

I’m happy to answer any questions you may have, just post a comment below.

About The Author

Ben currently works as a senior developer and technical business consultant outside of Boulder, Colorado.

More about this author

About Buink

Buink Web Development is a development shop founded in 2009 by Ben Buie. For years, Ben built and modified web assets for clients in Utah. In 2011, he moved the company to Colorado and in 2015 he started taking on new clients full-time.

Buink’s Core Values:

  • Cost effective technology (with business strategy in mind)
  • Eloquent, maintainable code
  • Responsive and transparent communication

Read more about Buink

Seth Lofgreen
Seth L.
21:36 29 Jun 19
Ben and team are incredible to work with. They are reliable and proficient. I'd highly recommend hiring them for web development work. SethVOLTAGE
Craig Adams
Craig A.
20:50 18 Jun 19
It was a pleasure to work with Ben and his team. It is rare to find such attention to high standards of coding and devops.
Lexi Steele
Lexi S.
15:36 18 Jun 19
Grateful to have Ben and his team as such a capable, reliable partner for completing client work!
Tom Showalter
Tom S.
13:18 14 Jun 19
I reached out to Buink after finding Ben’s name in a local developer/consultant listing in 2017, and I have to say, it has been an absolute pleasure to work with Buink. Ben consistently understands not just the development task laid in front of him but the business application behind the task. I’ve never felt more comfortable with a development team than I do with Buink. I truly feel Ben and his team are integral partners in the success of my business.read more
Craig Scribner
Craig S.
22:01 13 Jun 19
Buink saved my company's bacon at a very critical moment during my company's evolution. With almost no warning we had found ourselves stranded without any dev support, even though we had hundreds of users from big brands every day logging into our application and relying on things to keep working. We couldn't afford to have system failures, and I was amazed at—and will be forever grateful for—the way the Buink team stepped in and calmly assumed control of the craft. We and our clients were safe in their expert hands from that moment forward. I whole-heartedly recommend the quality of their work and the dedicated and ethical leadership they continually provide.read more
Marilyn Ference
Marilyn F.
22:47 13 May 19
I could not recommend Buink Web Development more highly. Ben and his team have recently developed a budgeting app for me (both web and IOS). I have had the opportunity of working with them for over a year and I am extremely happy with the results. I would say that the biggest plus for me is that I trust Ben completely. From the very first, Ben has helped me make decisions that were in the best interest of my company. I have never felt like he is taking advantage of me. Ben does his best to keep the whole process very open and upfront. I have really appreciated that.I tell people all the time that I love my developers. And I do. I'm very happy that I chose to use Buink to develop my apps. It was the best business decision I could have made.If you are looking for someone to develop a website or app, I strongly suggest choosing Buink Web Development. They are fantastic!Marilyn Ference, President, Defend Your Money, LLCread more
James Landon Buie
James Landon B.
01:33 28 Aug 18
Great company to help with all your web design needs!
Next Reviews

Connect with Buink

Connect with Buink via email, send us a message, or subscribe to our blog.